在类成员函数中使用常量变量的最快方法?

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

我想知道哪种是在以下三个选项之间使用常数变量的最有效方式。

const a = 1;
const b = 2;
const c = 3;

class Test {
    constructor(){
      this.a = 1;
      this.b = 2;
      this.c = 3;
    }
    optionA() {
      return a + b + c;
    }
    optionB() {
      return this.a + this.b + this.c;
    }
    optionC() {
      const _a = 1;
      const _b = 2;
      const _c = 3;
      return _a + _b + _c;
    }
}

我知道差异会很小,但是如果在大型“ for”循环中使用其中一个功能怎么办?与访问成员变量或全局变量相比,optionC()中的局部变量分配会花费更长的时间吗?如果我使用const而不是let,JavaScript会在内部进行优化吗?

javascript
3个回答
0
投票

仅通过阅读您的代码,optionA似乎是最有效的。但是,让我们使用控制台来测试该理论。

const a = 1;
const b = 2;
const c = 3;

class Test {
    constructor(){
      this.a = 1;
      this.b = 2;
      this.c = 3;
    }
    optionA() {
      return a + b + c;
    }
    optionB() {
      return this.a + this.b + this.c;
    }
    optionC() {
      const _a = 1;
      const _b = 2;
      const _c = 3;
      return _a + _b + _c;
    }
}

const lala = new Test();

console.log('Running each option once.');
console.time('a');lala.optionA();console.timeEnd('a');
console.time('b');lala.optionB();console.timeEnd('b');
console.time('c');lala.optionC();console.timeEnd('c');
console.log('---------------------------------');
console.log('Running each option 10,000 times.');
console.time('a');
for (let a = 0; a < 10000; a++) { lala.optionA(); }
console.timeEnd('a');
console.time('b');
for (let b = 0; b < 10000; b++) { lala.optionB(); }
console.timeEnd('b');
console.time('c');
for (let c = 0; c < 10000; c++) { lala.optionC(); }
console.timeEnd('c');
console.log('---------------------------------')

这显然不是很准确(因为选项A和C首先使对Class的需要无效...),但它为您提供了一些见识。

希望有所帮助。

干杯! 🍻


-1
投票

不知道它是否真的准确,但是您可以在jsbench上尝试使用它>


-1
投票

为什么不进行基准测试? https://jsben.ch/QPcBf

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