Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a speed difference in defining a JavaScript object literal with or without quotations marks?

In pure JavaScript, MDN and the Google JavaScript style guide suggest that the two snippets below are equivalent:

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

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

I've written a test function which 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 it is (marginally) faster to use quotation marks. Why would this be?

On my browser, I get these results from my test function, (average over 300 iterations):

With quotes: 167.6750966666926ms
Without quotes: 187.5536800000494ms

Of course, it's more than possible that my test function is duff too...

My browser: Chrome 29.0.1547.65

like image 631
jayp Avatar asked Sep 12 '13 18:09

jayp


1 Answers

I think it depends from your browser. The perfomance is approximately equivalent. http://jsperf.com/objectquotes

like image 92
Sorokin Evgeny Avatar answered Oct 22 '22 23:10

Sorokin Evgeny