Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I reuse one instance of GSON or create new ones on demand?

Tags:

java

json

gson

In most of my classes (especially server resources) I tend to create new instances of com.google.gson.Gson on demand. Sometimes I create them with the default constructor (for handling of simple POJOs), sometimes I use more sophisticated variants created with custom com.google.gson.GsonBuilder.

I know that Gson is a threadsafe class, so there is nothing standing against reusing the same instance of Gson instead of creating new ones. Heck, I might even reuse a static constant for this!

My question is this: should I create new instances whenever I need them, or should I create and use just one? What sort of performance implications will I be facing, if I serialize simple POJO with a Gson instance that was created with GsonBuilder and taught how to parse more complex data structures (had few custom serializers being registered)?

like image 224
ŁukaszBachman Avatar asked Jul 15 '15 14:07

ŁukaszBachman


People also ask

Can I reuse Gson?

Gson instances are Thread-safe so you can reuse them freely across multiple threads. You can create a Gson instance by invoking new Gson() if the default configuration is all you need.

Is Jackson better than Gson?

Big File Results: 2021. Last benchmarks Jackson was the winner, but this time GSON is by far the fastest, with JSONP being a close second and then followed by Jackson and then JSON. simple last.

Does Gson ignore extra fields?

3. Deserialize JSON With Extra Unknown Fields to Object. As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.

What is the difference between Gson and JSON?

GSON can use the Object definition to directly create an object of the desired type. While JSONObject needs to be parsed manually.


1 Answers

I know this is an old question but for future reference, the answer to this question is that you should go for the single instance if it is possible.

The creation of a GSON object is expensive depending on how many custom deserializer/serializer/handlers you register to it. I doubt that you will see any big performance boost from this.

About the second question, GSON internally has a list of registered serializer, and each one is checked against the object you are trying to parse. So you basically will add more iterations each time you register a custom serializer, but again, this is not a big performance issue compared to having a couple of big clumsy objects into memory.

like image 145
Aurasphere Avatar answered Oct 11 '22 08:10

Aurasphere