【发布时间】:2019-07-16 03:20:19
【问题描述】:
在 es6 类中,绑定 this(用于 react 事件处理程序),
像这样使用bind:
class BindFn {
constructor() {
this.fn = this.fn.bind(this);
}
fn() {}
}
或像这样使用arrow function:
class ArrowFn {
fn = () => {}
}
因为绑定是这样实现的:
const bind = function(scope) {
const fn = this;
return function(...args) {
return fn.apply(this, args);
};
};
所以当我们创建多个实例时,使用bind 将重用原型中的引用。使用arrow function 将创建不使用引用的新函数。
我写了一个html来测试,先用BindFn执行十次,每次记录时间和最大jsHeap在chrome中的性能。然后ArrowFn。
最后,我得到了这个:
use bind: spend time: 527.2 maxHeap: 173.4M
use arrow: spend time: 1081.2 maxHeap: 174.8M
内存使用差不多,我觉得使用bind会减少很多,为什么?
我的html正文代码:
class BindFn {
constructor() {
this.fn = this.fn.bind(this);
}
fn() {
const str = 'sdffsdfsdf'.repeat(999999);
return str
}
}
class ArrowFn {
fn = () => {
const str = 'sdffsdfsdf'.repeat(999999);
return str;
};
}
const objList = [];
let startTime = new Date();
for (let i = 0; i < 999999; i++) {
// objList.push(new BindFn());
objList.push(new ArrowFn());
}
console.log('spend time:' + (new Date() - startTime));
【问题讨论】:
-
请注意,您测量的是更接近 CPU 时间的东西 - 内存使用情况完全不同。如果您愿意,您也可以完全省略
fns 的主体,输出时间看起来相似。
标签: javascript memory bind es6-class arrow-functions