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

问题描述 投票:0回答:1

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

内存:据我了解,

sum2
将占用我创建的每个测试实例的内存,而
sum1
只会占用一次内存。

性能:如果我将

bind
与任何这些方法一起使用,它将创建一个包装函数,这将导致性能下降。

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

class Test {

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

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

}
javascript bind arrow-functions
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.