为什么使用或不使用引号来定义JavaScript对象文字有什么不同?

时间:2013-09-10 15:32:14

标签: javascript performance

在纯JavaScript中,MDNGoogle JavaScript style guide表明以下两个代码段是等效的:

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

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

但是,JSON规范要求使用引号。

在定义对象文字时,何时使用引号是否正确?这是否意味着对口译员有任何影响?

我编写了一个测试函数,它使用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 ......

1 个答案:

答案 0 :(得分:3)

  

属性的名称可以是任何字符串,包括空字符串。该   如果,对象文字中属性名称周围的引号是可选的   该名称将是合法的JavaScript名称,而不是保留字。所以   “first-name”周围需要引号,但周围是可选的   的如first_name 即可。

资料来源:Douglas Crockford的“JavaScript:The Good Parts”。