箭头函数、方法和绑定。内存使用率和性能

Arrow functions, methods and bind. Memory usage and performance

提问人:Vladimir 提问时间:8/14/2023 最后编辑:Jason AllerVladimir 更新时间:8/14/2023 访问量:110

问:

请检查下面的代码,我不确定我的JS是否正确,我通常使用TS。 我的问题是:这两种用法的内存使用率和性能有什么区别?

内存:据我了解,我创建的每个测试实例都会占用内存,而会做一次。sum2sum1

性能:如果我使用这些方法中的任何一个,它将创建一个包装函数,这将导致性能下降。bind

请推荐资源,我可以深入研究:方法与箭头函数 + 它们的绑定用法、内存消耗和性能 - 它们的缺点和优点

class Test {

  a = 100;
  
  constructor() {
    this.sum2 = (b) => this.a+b;
  }

  sum1(b) {
    return this.a+b;
  }

}
javascript 绑定 箭头函数

评论

3赞 Dave Newton 8/14/2023
您是否确定性能或内存消耗实际上是应用程序中的一个问题,还是这更像是理论问题?
0赞 Quentin 8/14/2023
“在这两种用法中,内存使用率和性能有什么区别” — 第 1 步:选择一个 JS 引擎进行性能测试。
0赞 Bergi 8/14/2023
箭头函数和绑定方法之间的差异可以忽略不计。如果你真的在乎,就自己测量一下。使用您更喜欢的那个。
0赞 Bergi 8/14/2023
通过原型定义方法与在构造函数中使用它的可能重复 - 真的是性能差异吗?

答:

1赞 Alexander Nenashev 8/14/2023 #1

它们在性能方面是相同的。 绑定版本速度更快,因为在调用时已经解析了上下文:

enter image description here

<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>

关于实例创建性能:也没有区别:enter image description here

<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>