5

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?

Bob Cross
  • 22,116
  • 12
  • 58
  • 95

1 Answers1

2

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.

Jesse Wilson
  • 39,078
  • 8
  • 121
  • 128
  • 1
    I've read your post and I don't see how it applies to the fundamental question above. Your article alludes to the workload involved in reflection but the `new Gson()` constructor doesn't do reflection on its own. Yes, it's true that `gson.toJSon(this)` is going to do some reflection but that's inherent in the use of JSON. Eventually, some reflection is going to happen. – Bob Cross Nov 29 '17 at 17:47
  • 1
    Each Gson instance caches all of the reflection it has done. If you create new Gson instances on each use, it has to do all of the reflection work on each use. – Jesse Wilson Nov 30 '17 at 18:05