声明 json - JSON.parse 与对象文字的性能

Performance of declaring json - JSON.parse vs object literal

根据 2019 年 Chrome 开发峰会视频,"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 显示出两者之间的主要区别。

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

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

在 javascript 中声明 json 时,使用 JSON.parse 而不是对象字面量有什么缺点吗?是否应始终使用 JSON.parse?

声明 json

没有缺点,JSON.parse returns 就像对象字面量给你的对象。

至于何时反对字面意思或不反对,请阅读下文。

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.

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

必读!!

你说 JSON.parse 更快,但如果你的对象尺寸很小,这是最糟糕的选择。

/* 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

性能相差数十倍

你的想法只能受对象大小写的影响,至少8Mb。

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