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

2.4k views Asked by At

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?

1

There are 1 answers

2
Jesse Wilson On

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.