Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparisions using ternary operator vs if else vs switch case (Performance)

I was searching for if-else vs ternary operator vs switch case but could not find any post with all the three comparisons. However, I came across some good posts and found that switch-case is faster than if-else. You may check the below one:

Why switch is faster than if

Then I came across some posts which said that there is no performance difference between if-else and the ternary operator. One of the most relevant posts is the following:

ternary operator vs. if statement: question of prettiness?

However, I did not find any relevant posts for switch-case vs ternary operator.

So, I just want to know if I can conclude that switch case is faster than both ternary operator and if-else?

I know this is a silly question but I want to know the answer.

like image 560
Viraj Pai Avatar asked Mar 31 '14 13:03

Viraj Pai


People also ask

Which is faster switch or ternary operator?

There should not be a major difference in speed. However, the switch is far more readable and maintainable. The switch option is easier to debug.

Is ternary operator more efficient than if-else?

If the condition is short and the true/false parts are short then a ternary operator is fine, but anything longer tends to be better in an if/else statement (in my opinion).

Is ternary operator slower than if-else?

Note that x86 is only slower when using ternary -- it is as equally fast as x64 when using if/else. So the question to answer is: "why is the X86 code so much slower than X64 when using the ternary operator?".

Is switch case faster than if-else?

A switch statement is significantly faster than an if-else ladder if there are many nested if-else's involved. This is due to the creation of a jump table for switch during compilation. As a result, instead of checking which case is satisfied throughout execution, it just decides which case must be completed.


1 Answers

If switch < if-then-else and if-then-else == ternary, then switch < ternary.

like image 141
Trenin Avatar answered Sep 30 '22 08:09

Trenin