Should I parse json string to json object or manipulate the string directly

Viewed 1187

normally I parse a json string to json object instead of manipulating the json string directly. for example, a json string like

{"number": "1234567"}

if I have to add 000 at the end

...
{...,"number" : "1234567000",...}
....

I will use jackson either parse it as Json Object or POJO

I understand readability perspective parsing to Json object or POJO is much better, but I'm curious about the performance. In this case, if I manipulate the json string directly, I have to use regex to extract the number attribute, and add 000 at the end, which is much more expensive than parsing to Json Object if having lots of data? because string object basically creates a new string object?

EDIT: Based on @Itai Steinherz's link I also make a benchmark in JS, and it shows json parse is better https://jsbench.me/93jr1w6k5b/1

1 Answers

Since I'm not very familiar with JSON parsing/manipulation in Java, I'll compare the same operations in JavaScript (which I am more experienced in).

Comparing using a basic regex with .replace and using JSON.parse & JSON.stringify, the result are that using JSON.parse is slower by a small percentage (4.37% to be precise).

However, I don't think the perf gain is worth it, and I would always go with more readable and maintainable code (the JSON.parse approach) rather than the more performant (the .replace approach).

See the complete benchmark I used here.

Related