Reputation: 1271
I'm using Groovy JsonSlurper
parsing json. I found that I should initialize a JsonSlurper
instance before I call parseText()
method.
When I have multiple json objects (e.g. a LinkedList<String>
with n
json texts) to parse, should I initialize n
JsonSlurper
or initialize a JsonSlurper
and call its parseText
n
times?
When I use JsonSlurper
on a Web Server, is that the best practice to just maintain one global JsonSlurper
instance and use it everywhere? Or initialize an instance every time I receive an HTTP request?
Or to be more clear, what the constructor of JsonSlurper
do?
Upvotes: 2
Views: 1209
Reputation: 42264
You can think of JsonSlurper
as a facade for creating a concrete JSON parser implementation. For instance, the default parser that gets created anytime you invoke parse()
or parseText()
methods is JsonParserCharArray
. If you take a look at JsonSlurper
source code you will see that it encapsulates the following five private fields:
private int maxSizeForInMemory = 2000000;
private boolean chop = false;
private boolean lazyChop = true;
private boolean checkDates = true;
private JsonParserType type = JsonParserType.CHAR_BUFFER;
When you create JsonSlurper
you use these default values, but for any specific use case, you can modify them to fit best your needs.
Answering your first question, it does make sense to instantiate a single JsonSlurper
and use to parse all Strings while iterating the list. Something like :
def slurper = new JsonSlurper()
def parsed = jsons.collect { slurper.parseText(it) }
If your list is size 1000 let's say, it will create a single JsonSlurper
object and 1000 JsonParser
objects, instead of 1000 JsonSlurper
objects and 1000 JsonParser
objects.
Answering your second question, there is no good context-free answer to this question. It highly depends on a few factors like the server load, JSON serialization/deserialization frequency, available memory, JsonSlurper
use cases and so on. You actually have to monitor your application and experiment with both approaches to see what works better for you. For instance, if your application handles HTTP requests constantly and it constantly creates the same JsonSlurper
and uses exactly the same default values, then you might consider creating a singleton-like bean that injects the same instance of JsonSlurper
to handle every HTTP request. But on the other hand, if your application does not suffer from tons of parallel requests and it handles a few sequential requests on average, then keeping a JsonSlurper
object in memory for all the time may sound like a wasteful resources utilization.
Upvotes: 2