Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of declaring json - JSON.parse vs object literal

According to the 2019 Chrome Dev Summit video, "Faster apps with JSON.parse", using JSON.parse with a string literal instead of declaring the json through an object literal results in a noticeable speed improvement. The google JSON.parse benchmarks show a major difference between the two.

//JS object literal
const data = { foo: 42, bar: 1337 }; // 🐌

//JSON.parse 20%+ faster
const data = JSON.parse('{"foo":42,"bar":1337}'); // 🚀

When declaring json in javascript, are there any downsides of using JSON.parse instead an object literal? Should json always be declared using the JSON.parse?

like image 471
Eugene Avatar asked Oct 15 '25 12:10

Eugene


2 Answers

There's no downside, JSON.parse returns an object just like the object literal gives you.

As for when to object literal or not read below.

As long as the JSON string is only evaluated once, the JSON.parse approach is much faster compared to the JavaScript object literal, especially for cold loads. A good rule of thumb is to apply this technique for objects of 10 kB or larger — but as always with performance advice, measure the actual impact before making any changes.

Source: https://v8.dev/blog/cost-of-javascript-2019

like image 74
qkombur Avatar answered Oct 17 '25 00:10

qkombur


MUST READ!!

You said JSON.parse is faster, but this is the worst choice if your objects size are small.

/* JSON.parse */
start = new Date();

for(i=0; i<1000000; i++){ //create from JSON
const miniObjectFromJson = JSON.parse('{"foo":42,"bar":1337}');
}
end = new Date()
timeGap = end - start; //457

/* JS object literal */
start = new Date()

for(i=0; i<1000000; i++){ //create from JS Object Literal
const miniObjectFromLiteral = { foo: 42, bar: 1337 };
}
end = new Date()
timeGap = end - start; //9

There is a performance difference of tens of times.

Your thoughts can only be affected by the massive size of the object case, at least 8Mb.

reference: https://www.youtube.com/watch?v=ff4fgQxPaO0

like image 24
yoonsukhyun Avatar answered Oct 17 '25 01:10

yoonsukhyun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!