什么使两个相同的对象性能不同?

资源

使用gettersetter定义两个对象,使用相同的代码

node v7.3.0使用benchmark.js进行testing

 const builtInObject1 = (function (object) { let lastA = 1; return Object.defineProperties(object, { a:{ get(){ return lastA }, set(newValue){ lastA = newValue; } } }) })({}); const builtInObject2 = (function (object) { let lastA = 1; return Object.defineProperties(object, { a:{ get(){ return lastA }, set(newValue){ lastA = newValue; } } }) })({}); 

〜增加es2015getter/setter情况

 const builtInObject3 = (function () { let lastA = 1; return { get a(){ return lastA }, set a(value){ lastA = value; } } })(); 

 const builtInObject4 = (function (object) { let last = 1; return Object.defineProperties(object, { b:{ get(){ return last }, set(newValue){ last = newValue; } } }) })({}); const builtInObject5 = (function (object) { let last = 1; return Object.defineProperties(object, { c:{ get(){ return last }, set(newValue){ last = newValue; } } }) })({}); 

 (new Benchmark.Suite("object-assign-properties")) .add("#built-in object1.a getter and setter", function () { builtInObject1.a = builtInObject1.a + 1; }) .add("#built-in object2.a getter and setter", function () { builtInObject2.a = builtInObject2.a + 1; }) .add("#built-in object3.a es6 getter and setter", function () { builtInObject3.a = builtInObject3.a + 1; }) .add("#built-in object4.b getter and setter", function () { builtInObject4.b = builtInObject4.b + 1; }) .add("#built-in object5.c getter and setter", function () { builtInObject5.c = builtInObject5.c + 1; }) .on('cycle', function(event) { console.log(String(event.target)); }) .on('complete', function() { console.log('Fastest is ' + this.filter('fastest').map('name')); }) .run({ 'async': false }); 

结果

 #built-in object1.a getter and setter x 80,459,419 ops/sec ±0.65% (88 runs sampled) #built-in object2.a getter and setter x 3,967,313 ops/sec ±0.36% (91 runs sampled) #built-in object3.a es6 getter and setter x 3,982,725 ops/sec ±0.51% (93 runs sampled) #built-in object4.b getter and setter x 79,608,022 ops/sec ±4.06% (87 runs sampled) #built-in object5.c getter and setter x 78,849,808 ops/sec ±0.82% (92 runs sampled) Fastest is #built-in object1.a getter and setter 

ops/sec这些testing结果之间的差异让我感到困惑

为什么???

是什么使这些差异?

accroding给蓝鸟| 优化杀手 , object3不会被优化,但为什么object2得到这么慢?

参考?

  • jsperftesting,似乎两个testing在我的浏览器(osx Chrome Canary 57,CPU:i7)中运行优化的代码,刚刚得到3,800,000 opt / sec
    • https://jsperf.com/what-makes-two-same-objects-performance-different/1
    • https://jsperf.com/what-makes-two-same-objects-performance-different/3

相关链接

  • github / bestiejs / benchmark.js | 问题#184
  • github / nodejs / help | #442