Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How expensive is the new Gson() constructor in production?

I am creating a new Netty pipeline and I am trying to:

  1. avoid premature optimization.
  2. write code that is easy to explain to one of my interns.

This sort of factory method is certainly easy to explain:

public String toJSON()
{
    Gson gson = new Gson();
    return gson.toJson(this);
}

In a somewhat related question, the OP asks if it is OK (meaning thread-safe) to re-use a single instance of a Gson object. My question is slightly different: is there a good reason to share the object? If so, at what level of complexity is it worth sharing the Gson object? Where is the trade-off?

like image 561
Bob Cross Avatar asked Oct 29 '22 22:10

Bob Cross


1 Answers

It’s expensive, and the cost scales with the complexity of the data models you're using Gson to bind. I wrote a post, Reflection Machines, that explains why creating Gson instances is expensive and should be minimized.

like image 133
Jesse Wilson Avatar answered Nov 14 '22 03:11

Jesse Wilson