绑定和箭头函数的内存消耗与理论不一致

时间:2019-02-22 04:38:09

标签: javascript memory bind es6-class arrow-functions

在es6类中,要绑定此(用于react事件处理程序),

像这样使用bind

class BindFn {
    constructor() {
        this.fn = this.fn.bind(this);
    }
    fn() {}
}

或像这样使用arrow function

class ArrowFn {
    fn = () => {}
}

因为bind是这样的工具:

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

内存使用类似,我认为使用绑定会减少很多,为什么?

我的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));

1 个答案:

答案 0 :(得分:0)

在BindFn和ArrowFn中,您都为每个实例创建了函数。

此行为每个Bindfn实例创建一个fn函数:

this.fn = this.fn.bind(this);