gpt4 book ai didi

javascript - 为什么在定义带有或不带引号的 JavaScript 对象字面量时速度会有所不同?

转载 作者:数据小太阳 更新时间:2023-10-29 04:17:12 24 4
gpt4 key购买 nike

在纯 JavaScript 中,MDNGoogle JavaScript style guide建议以下两个片段是等效的:

// Snippet one
var myObject = {
"test":"test"
}

// Snippet two
var myObject = {
test:"test"
}

我编写了一个测试函数,它使用 performance.now() ( MDN ) 来测量创建一百万个简单对象所花费的时间:

function test(iterations) {
var withQuotes = [];
var withoutQuotes = [];

function testQuotes() {
var objects = [];
var startTime, endTime, elapsedTimeWithQuotes, elapsedTimeWithoutQuotes;

// With quotes
startTime = window.performance.now();

for (var i = 0; i < 1000000; i++) {
objects[objects.length] = {
"test": "test"
};
}

endTime = window.performance.now();
elapsedTimeWithQuotes = endTime - startTime;

// reset
objects = undefined;
startTime = undefined;
endTime = undefined;
objects = [];

// Without quotes
startTime = window.performance.now();

for (var i = 0; i < 1000000; i++) {
objects[objects.length] = {
test: "test"
};
}

endTime = window.performance.now();
elapsedTimeWithoutQuotes = endTime - startTime;

return {
withQuotes: elapsedTimeWithQuotes,
withoutQuotes: elapsedTimeWithoutQuotes
};
}

for (var y = 0; y < iterations; y++) {
var result = testQuotes();
withQuotes[withQuotes.length] = result.withQuotes;
withoutQuotes[withoutQuotes.length] = result.withoutQuotes;

console.log("Iteration ", y);
console.log("With quotes: ", result.withQuotes);
console.log("Without quotes: ", result.withoutQuotes);
}

console.log("\n\n==========================\n\n");
console.log("With quotes average: ", (eval(withQuotes.join("+")) / withQuotes.length));
console.log("Without quotes average: ", (eval(withoutQuotes.join("+")) / withoutQuotes.length));
}

test(300);

我得到的结果表明使用引号(略微)更快。为什么会这样?

在我的浏览器上,我从我的测试函数中得到了这些结果(平均超过 300 次迭代):

带引号:167.6750966666926ms
没有引号:187.5536800000494ms

当然,也有可能我的测试函数也是duff...

我的浏览器: Chrome 29.0.1547.65

最佳答案

我认为这取决于您的浏览器。性能大致相当。 http://jsperf.com/objectquotes

关于javascript - 为什么在定义带有或不带引号的 JavaScript 对象字面量时速度会有所不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18771981/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com