In pure JavaScript, MDN and the JavaScript JavaScript Style Guide assume that the two fragments below are equivalent:
// Snippet one var myObject = { "test":"test" } // Snippet two var myObject = { test:"test" }
However, the JSON specification requires the use of quotation marks.
When to use quotation marks when defining an object literal, if at all? Does this / have any meaning for the translator?
I wrote a test function that uses performance.now()
( MDN ) to measure the time it takes to create a million simple objects:
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);
The results I get imply that they (to a lesser extent) use quotation marks faster. Why should it be?
In my browser, I get these results from my test function (an average of over 300 iterations):
With quotes : 167.6750966666926ms
Without quotes : 187.5536800000494ms
Of course, it is more than possible that my test function is also duff ...
jayp source share