【问题标题】:Which of the boolean operators is more optimised?哪个布尔运算符更优化?
【发布时间】:2020-04-02 17:55:25
【问题描述】:

我正在通过 Node.js 框架使用 JavaScript。

我有以下 if 语句。

if (this.LRR && this.LRR._DataStore === Key) return this.LRR;

我有:

if ((this.LRR || {})._DataStore === Key) return this.LRR;

假设this.LRR 是一个对象,但默认情况下null。哪个更优化?

【问题讨论】:

  • 你真的参加过赛马吗? ericlippert.com/2012/12/17/performance-rant
  • 这是一个严肃的问题吗?为什么这可能很重要?如果你有正当理由知道,那么它可能取决于特定的 JS 解释器,你只需要在你关心的解释器中测试这两个选项。但是,这有 99.999% 的可能性是过早的优化,或者是试图优化您花时间优化的 100 件最重要的事情之一以外的事情。

标签: javascript node.js optimization


【解决方案1】:

由于 JavaScript 的Short-circuit evaluation,只要在false 之后遇到&&,就会停止执行。

所以在你的情况下,第一个更优化和高效

if (this.LRR && this.LRR._DataStore === Key) return this.LRR;
              ^
              |
Execution stops right at here

而在第二种情况下,整个条件被执行

if ((this.LRR || {})._DataStore === Key) return this.LRR;
// => if (({})._DataStore === Key) return this.LRR;
// => if (undefined === Key) return this.LRR;
                           ^
                           |
Execution stops right at here

【讨论】:

    【解决方案2】:

    我没有 node.js,但这可能会对你有所帮助

    optimalisationTest();
    
    function optimalisationTest() {
        let startTime = Date.now();
        console.log(startTime);
    
        //Test with maybe even 1000000 to check what is faster.
        for (let i = 0; i < 1000; i++) {
            //Test this first. After remove this line below and change it to the other if statement u have. Check what is faster.
            if (this.LRR && this.LRR._DataStore === Key) return this.LRR;
        }
    
        let endTime = Date.now();
        console.log(endTime);
    
        //End time - begin time to check how long it took to execute the code.
        console.log(endTime - startTime);
    }
    

    我不确定您的 if 语句是否不止一次,但请告诉我结果。

    【讨论】:

      【解决方案3】:

      这个

      if (this.LRR && this.LRR._DataStore === Key) return this.LRR;
      

      发生短路并避免采用新对象然后采用属性来检查值。

      如果可能,您可以拨打optional chaining operator ?.

      if (this.LRR?._DataStore === Key) return this.LRR;
      

      【讨论】:

      • 我没有投反对票,但 OP 提出了一个性能问题,而不是如何做到这一点。
      • 我从来不知道这是一件事,但我并不感到惊讶。遗憾的是,Node 框架不支持这一点。
      猜你喜欢
      • 1970-01-01
      • 2010-11-29
      • 2012-09-11
      • 2011-12-29
      • 1970-01-01
      • 2013-02-01
      • 2011-04-20
      • 2011-09-27
      相关资源
      最近更新 更多