关于性能:为什么定义带有或不带引号的JavaScript对象文字有什么不同?

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

本问题已经有最佳答案,请猛点这里访问。

在纯JavaScript中,MDN和Google JavaScript样式指南建议下面的两个片段是等效的:

1
2
3
4
5
6
7
8
9
// Snippet one
var myObject = {
 "test":"test"
}

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

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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("

==========================

"
);
  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

当然,我的测试功能也是可能的...


A property's name can be any string, including the empty string. The
quotes around a property's name in an object literal are optional if
the name would be a legal JavaScript name and not a reserved word. So
quotes are required around"first-name", but are optional around
first_name.

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