请检查下面的代码,我不确定我的JS是否正确,我通常使用TS。 我的问题是:这两种用法在内存使用和性能上有什么区别
内存:据我了解,
sum2
将占用我创建的每个测试实例的内存,而sum1
只会占用一次内存。
性能:如果我将
bind
与任何这些方法一起使用,它将创建一个包装函数,这将导致性能下降。
请推荐资源,我可以在其中深入研究:方法与箭头函数+它们的绑定用法,内存消耗和性能 - 它们的缺点和优点
class Test {
a = 100;
constructor() {
this.sum2 = (b) => this.a+b;
}
sum1(b) {
return this.a+b;
}
}
它们在性能方面是相同的。 绑定版本更快,因为上下文已经在调用时解析:
<script benchmark data-count="1000000000">
class Test {
a = 100;
constructor() {
this.sum2 = (b) => this.a+b;
}
sum1(b) {
return this.a+b;
}
sum3 = function(b){
return this.a+b;
}
}
const test = new Test;
const method = test.sum1.bind(test);
const func = test.sum3.bind(test);
// @benchmark arrow
test.sum2(100);
// @benchmark method
test.sum1(100);
// @benchmark bound method
method(100);
// @benchmark function
test.sum3(100);
// @benchmark bound function
func(100);
</script>
<script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>