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

JavascriptPerformance

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

Seems like nobody did any actual profiling. Here's the code I used:

test = function() {
    for (var i = 0; i < 10000000; i++) {
        var a = i < 100 ? 1 : 2;

        /*
        if(i < 100) {
            var a = 1;
        }else{
            var a = 2;
        }
        */
    }
}

test();

Using the if/else block instead of the ternary operator yields a 1.5 - 2x performance increase in Google Chrome v21 under OS X Snow Leopard.

As one use case where this is very important, synthesizing real-time audio is becoming more and more common with JavaScript. This type of performance difference is a big deal when an algorithm is running 44100 times a second.

Solution 2 - Javascript

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;

Solution 3 - Javascript

The speed difference will be negligible - use whichever you find to be more readable. In other words I highly doubt that a bottleneck in your code will be due to using the wrong conditional construct.

Solution 4 - Javascript

to charlie roberts' answer above, I would add:

the following link gives some incisive answers; the result for switches in Firefox being the most striking: http://jsperf.com/if-else-vs-arrays-vs-switch-vs-ternary/39

Those who question why anyone would investigate optimization to this degree would do well to research WebGL!

Solution 5 - Javascript

Ternary operator is only syntactic sugar, not a performance booster.

Solution 6 - Javascript

I'm doing another syntax:

var a = true,
    b;

b = (a == false) 
    ? true // if a == false, b = true
    : false; // else: a == true so b = false

    /* Equivalent of
    if(a == true)
      var b = true;
    else
      var b = false;

Some people like my code and tell me it's simple to read.

Solution 7 - Javascript

I think this will helps to find exact speed difference of the if..else and ternary operator. I checked different types of nested conditions for both ternary and if else. it shows ternary is more faster than if..else statement(Nodejs console, Chrome and Edge) but in the case of Firefox, shows opposite result (Windows 10). The below code gives the 40 average milliseconds for both test.

const IfTest = () => {
  let sum = 0;
  for (let x = 0; x < 1e8; ++x) {
    if (x % 2 === 0) 
     sum += x;
    else if (x > 1e8 / 2) 
     sum += 5;
    else 
     sum += 6;
  }
};

const TernaryTest = () => {
  let sum = 0;
  for (let x = 0; x < 1e8; ++x) {
    sum += x % 2 === 0 ? x : x > 1e8 / 2 ? 5 : 6;
  }
};

const initTest = (e) => {
  let [tAverage, ifAverage] = [0, 0];
  for (let x = 0; x < e; ++x) {
    const date = new Date;
    IfTest();
    ifAverage += new Date - date;
  }
  console.log("if execution time:", ifAverage / e);

  for (let x = 0; x < e; ++x) {
    const date = new Date;
    TernaryTest();
    tAverage += new Date - date;
  }
  console.log("ternary execution time:", tAverage / e);
};

initTest(40);

Solution 8 - Javascript

There is no difference in speed.

Some prefer the if/else for readability. Personally, I use the ternary operator whenever the logic is trivial enough to understand on one line.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeffView Question on Stackoverflow
Solution 1 - Javascriptcharlie robertsView Answer on Stackoverflow
Solution 2 - JavascriptAndrew LuhringView Answer on Stackoverflow
Solution 3 - JavascriptAndrew HareView Answer on Stackoverflow
Solution 4 - JavascriptJay EdwardsView Answer on Stackoverflow
Solution 5 - Javascriptcwalsh003View Answer on Stackoverflow
Solution 6 - JavascriptDelbo arView Answer on Stackoverflow
Solution 7 - JavascriptKelvin PaulView Answer on Stackoverflow
Solution 8 - JavascriptErixView Answer on Stackoverflow