两个`一模一样`的object先后定义为什么会有巨大的性能差异?
先后定义两个带setter
和getter
的对象, 然后在node v7.3.0
, 用benchmark.js
测试
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;
}
}
})
})({});
//补充es6的`get`和`set`属性定义方法
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
object1
和object2
的定义方式是一模一样的,但object1
比object2
和object3
快十多倍!
2017-01-15 19:41
补充了object4
和object5
, 的执行效率和object1
几乎是一样的。
根据 <bluebird | Optimization-killers (译文)> object3
即es6的写法目前仍然不会被优化, 但是问题还是回到了为什么object2
和object1
相比会慢这么多呢???
为什么呢 ???
关联连接
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论