提问人:Vladimir 提问时间:8/14/2023 最后编辑:Jason AllerVladimir 更新时间:8/14/2023 访问量:110
箭头函数、方法和绑定。内存使用率和性能
Arrow functions, methods and bind. Memory usage and performance
问:
请检查下面的代码,我不确定我的JS是否正确,我通常使用TS。 我的问题是:这两种用法的内存使用率和性能有什么区别?
内存:据我了解,我创建的每个测试实例都会占用内存,而会做一次。sum2
sum1
性能:如果我使用这些方法中的任何一个,它将创建一个包装函数,这将导致性能下降。bind
请推荐资源,我可以深入研究:方法与箭头函数 + 它们的绑定用法、内存消耗和性能 - 它们的缺点和优点
class Test {
a = 100;
constructor() {
this.sum2 = (b) => this.a+b;
}
sum1(b) {
return this.a+b;
}
}
答:
1赞
Alexander Nenashev
8/14/2023
#1
它们在性能方面是相同的。 绑定版本速度更快,因为在调用时已经解析了上下文:
<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>
<script benchmark data-count="1000000000">
class TestArrow {
sum = (a, b) => a + b;
}
class TestMethod {
sum(a, b){ return a + b; }
}
class TestFunction {
sum = function (a, b){ return a + b; }
}
// @benchmark arrow
new TestArrow;
// @benchmark method
new TestMethod;
// @benchmark function
new TestFunction;
</script>
<script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>
评论