PeterMmm
PeterMmm

Reputation: 24630

JSON performance

I have to turn a List<Map> into a JSON string. The Maps are flat and containing primitive and String data. Right now I'm using GSON. Basically like this:

List<Map> list = new ArrayList();

Map map = new HashMap();
map.put("id",100);
map.put("name","Joe");
map.put("country","US");
// ...
list.add(map);

Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create(); 
Stopwatch sw = Stopwatch.createStarted(); // guava's stopwatch 
String s = gson.toJson(list);
System.err.println("toJson laps " + sw);
return s;

The list may have 100 entries and each map aprox. 20 fields. GSON really takes long time to create the JSON string. The JSON string will be returned by a HTTP response and right now it took too much time (8000ms). So I try other ones: json-smart, jackson, etc. But no one gives a significant speed boost. I trace the JSON string creation as the hot spot in execution time.

For 100 x 20 fields I really won't expect more than a second but it takes significant much more time. Is there any heal for this ?

Update I have overseen some BLOB data that is returned. Thank you all.

Upvotes: 0

Views: 4472

Answers (2)

fabien
fabien

Reputation: 1549

  1. If you want to write benchmarks, use JMH. Writing high quality benchmarks isn't easy and JMH does a lot of the heavy lifting for you (although there are still a few gotchas).
  2. If you wonder which Java Json library serializes/deserializes faster for various payload sizes, you can look at this extensive benchmark which compares a dozen of them with JMH. Fasted is dsljson, second is jackson. Gson is actually pretty slow for a 'modern' lib.

Upvotes: 0

Stefaan Neyts
Stefaan Neyts

Reputation: 2067

You better use Jackson2

https://github.com/FasterXML/jackson

Java EE 7 has also a new JSON processing API, brand new!

http://docs.oracle.com/javaee/7/api/javax/json/package-summary.html

Profiling the different libs will provide answers. For enterprise applications, I never use GSON.

Upvotes: 2

Related Questions