falcon
falcon

Reputation: 1434

Caching JSON string vs Java Object

in one of my web services, I am caching the result using memcached. I can either cache the result json or the source object. But if i cache the source object, i have to convert it to json everytime before sending the result(I am doing it in my code because i'm using json views to dynamiccaly restrict few columns). If i cache my JSON String(considerably large), i just have to return it. My question is, will JSON string consume more memory than the java object or is it a bad idea to cache JSON strings?

Upvotes: 1

Views: 3454

Answers (1)

cruftex
cruftex

Reputation: 5723

If you cache the source object via memcache, it has to be serialized and deserialized. Which is a lot of overhead. So caching the JSON object is faster.

Two advices on this:

Avoid the character encoding: If possible store the JSON object as byte array and not as string or char array and return it via HttpResponse.getOutputStream(json). This way you also bypass the additional character encoding.

Cache the whole response: If the JSON is a result of a REST query, it is event better to cache the complete request via a caching server in front of your application (e.g. varnish, nginx, apache traffic server.). Just put the right http cache headers on it and you are fine.

Upvotes: 2

Related Questions