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)?
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.
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.
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.
GSON can use the Object definition to directly create an object of the desired type. While JSONObject needs to be parsed manually.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With