Is ternary operator, if-else or logical OR faster in javascript?

后端 未结 7 1571
情歌与酒
情歌与酒 2020-11-30 02:06

Which method is faster or more responsive in javascript, if-else, the ternary operator or logical OR? Which is advisable to use, for what reasons?

7条回答
  •  粉色の甜心
    2020-11-30 02:48

    I didn't think @charlie robert's test was fair

    Here's my jsperf

    result:

    1. strict equal is the fastest
    2. strict ternary is 33% slower
    3. truthy falsy is 49% slower
    4. ternary truthy falsy is 55% slower
    5. if else and ternary are roughly the same.

    normal equal and normal ternary slowest.

    strict equals:

    var a = true, b;
    
    if (a === true) {
      b = true;
    } else {
      b = false
    }
    if (a === false) {
      b = true;
    } else {
      b = false;
    }
    

    ternary strict equals

    var a = true, b;
    
    b = (a === true) ? true : false;
    
    b = (a === false) ? true : false;
    

    simple equality

     var a = true, b;
    
        if (a == true) {
          b = true;
        } else {
          b = false;
        }
    
        if (a == false) {
          b = true;
        } else {
          b = false;
        }
    

    simple ternary equality

     var a = true, b;
        b = (a == true) ? true : false;
    
        b = (a == false) ? true : false;
    

    truthy / falsy

    var a = true, b;
    if (a) {
      b = true;
    } else {
      b = false;
    }
    
    if (!a) {
      b = true;
    } else {
      b = false;
    }
    

    ternary truthy / falsy

    var a = true, b;
    b = (a) ? true : false;
    b = (!a) ? true : false;
    

提交回复
热议问题