Skip to content

Instantly share code, notes, and snippets.

@qwwdfsad
Created March 4, 2016 21:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qwwdfsad/a72692ab56a1a946a5fb to your computer and use it in GitHub Desktop.
Save qwwdfsad/a72692ab56a1a946a5fb to your computer and use it in GitHub Desktop.
package org.qwwdfsad.benchmarks;
import com.google.gson.Gson;
import org.openjdk.jmh.annotations.*;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Threads(8)
@Fork(value = 2)
@Warmup(iterations = 10)
@Measurement(iterations = 10)
@State(Scope.Thread)
public class GsonBenchmark {
private static final Gson GSON = new Gson();
private static final ThreadLocal<Gson> THREAD_LOCAL_GSON = new ThreadLocal<Gson>() {
@Override
protected Gson initialValue() {
return new Gson();
}
};
public static class Pojo {
boolean bool;
int i;
long l;
double d;
String s;
public Pojo(boolean bool, int i, long l, double d, String s) {
this.bool = bool;
this.i = i;
this.l = l;
this.d = d;
this.s = s;
}
}
// JMH allows using instance field as single state object
private Pojo state = buildState();
private Pojo buildState() {
return new Pojo(true, 1, 2L, 3.0, "4");
}
@Benchmark
public String deserializeThreadLocal() {
return THREAD_LOCAL_GSON.get().toJson(state);
}
@Benchmark
public String deserializeContended() {
return GSON.toJson(state);
}
}
Original gson (2.6.3-SNAPSHOT)
Contended case:
java -jar target/benchmarks.jar -t -8 -gc true GsonBenchmark
Benchmark Mode Cnt Score Error Units
GsonBenchmark.deserializeContended thrpt 20 1192.009 ± 49.979 ops/ms
GsonBenchmark.deserializeThreadLocal thrpt 20 3645.967 ± 82.016 ops/ms
Sanity check: benchmark with only 1 thread should show ~same throughput for both plain and thread local Gson:
java -jar target/benchmarks.jar -t 1 -gc true GsonBenchmark
Benchmark Mode Cnt Score Error Units
GsonBenchmark.deserializeContended thrpt 20 1011.861 ± 32.744 ops/ms
GsonBenchmark.deserializeThreadLocal thrpt 20 1088.537 ± 31.451 ops/ms
For patched Gson:
java -jar target/benchmarks.jar -t -8 -gc true GsonBenchmark
GsonBenchmark.deserializeContended thrpt 20 4003.211 ± 164.599 ops/ms
GsonBenchmark.deserializeThreadLocal thrpt 20 3997.017 ± 211.468 ops/ms
java -jar target/benchmarks.jar -t 1 -gc true GsonBenchmark
GsonBenchmark.deserializeContended thrpt 20 1160.261 ± 25.967 ops/ms
GsonBenchmark.deserializeThreadLocal thrpt 20 1131.689 ± 17.576 ops/ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment