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

问题: 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...

问题:

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:

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.

  • 发表于 2019-01-19 04:15
  • 阅读 ( 176 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除