Skip to content

Performance improvement using Jackson ObjectWriter? #28

@cchacin

Description

@cchacin

From Jackson's best practices:

7. Prefer ObjectReader/ObjectWriter over ObjectMapper
Although the main reason to prefer these objects is thread-safety (and thus correctness), there may be performance benefits as well. Latest Jackson versions (2.1 and above) will be able to reuse root-level (de)serializers, making reuse of ObjectReaders and ObjectWriters bit more efficient than using ObjectMapper.

I notice in that the TsdLogSink.record method is using objectMapper.writeValueAsString, even when we use a serializer with the Streaming API we should take a look to the possible performance improvements with the writers/readers instead.

I write this simple benchmark using JMH to verify this, but would be great to have the same for the TsdLogSink methods:

@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@Warmup(iterations = 16,
        time = 2500,
        timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 16,
             time = 2500,
             timeUnit = TimeUnit.MILLISECONDS)
@Fork(1)
@State(Scope.Benchmark)
public class JacksonBenchmark {
    private ObjectMapper objectMapper;
    private ObjectWriter objectWriter;
    private Pojo         pojo;

    @Setup
    public void start() throws Exception {
        this.objectMapper = new ObjectMapper();
        this.objectWriter = this.objectMapper.writerFor(Pojo.class);
        this.pojo = new Pojo();
        this.pojo.a = 1;
        this.pojo.b = 1;
        this.pojo.c = "1";
        this.pojo.d = true;
        this.pojo.e = false;
        this.pojo.f = 1L;
        this.pojo.g = 1L;
    }

    @Benchmark
    public String serializeWithObjectMapper() throws Exception {
        return this.objectMapper.writeValueAsString(this.pojo);
    }

    @Benchmark
    public String serializeWithObjectWriter() throws Exception {
        return this.objectWriter.writeValueAsString(this.pojo);
    }

    public static final class Pojo {
        public int     a;
        public Integer b;
        public String  c;
        public boolean d;
        public Boolean e;
        public long    f;
        public Long    g;
    }
}

RESULTS

Result "serializeWithObjectMapper":
  2101050.903 ±(99.9%) 13548.612 ops/s [Average]
  (min, avg, max) = (2085229.061, 2101050.903, 2127269.712), stdev = 13306.549
  CI (99.9%): [2087502.290, 2114599.515] (assumes normal distribution)
Result "serializeWithObjectWriter":
  2137441.318 ±(99.9%) 19695.087 ops/s [Average]
  (min, avg, max) = (2104353.144, 2137441.318, 2173609.575), stdev = 19343.209
  CI (99.9%): [2117746.231, 2157136.406] (assumes normal distribution)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions