This project has moved and is read-only. For the latest updates, please go here.

JsonSerializer - thread safe?

Feb 21, 2010 at 3:07 PM

It looks like holding one instance of the JsonSerializer is much faster than creating the instance per deserialize/serialize request.

I'm guessing this is due to extensive caching we've got in this class.
Does JsonSerializer meant to be thread-safe or should I protect the calls? This will obviously make me thing about how wasteful will it be to hold a lock .vs. create new instance every time.

My usage is heavy traffic web site, with ~25 json deserialization calls (.net calls java services), each cost around 4ms when creating the serializer every time and ~0.5ms when using single instance. This is huge difference !

How do you recommend using this class?


Feb 22, 2010 at 6:57 AM

It is thread safe but all that happens when a JsonSerializer is created are some properties being set.

Feb 22, 2010 at 7:54 AM

I've get a simple console application that proves my point.

creating instance every time:

-- it looks like the more I call Deserialize, the avg time it takes to deserialize the json string is getting smaller, until ~20ms or so (with a specific data + object). Then the time stays the same.

creating one instance: 

-- it looks like the first call is expensive and the rest is almost 0ms. 

This makes me think that some of the caching there is probably instance based, thus the drastic change.
How can I send it to you the example?

Feb 22, 2010 at 9:19 PM

Weird. There is caching but it is static across all JsonSerializers.

You can upload code here - I'd be interested to take a look.

Feb 23, 2010 at 7:09 AM

uploaded, patch ID: 5343

Thanks James for your effort and responsiveness.
We really enjoy using your library and appreciate your time.

Feb 24, 2010 at 9:35 AM

Ah ok - caching is done inside the contract resolver and you are creating a new one each time. I might make some changes around this area.

You are safe to share a static JsonSerializer to improve performance.