5

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.

Community
  • 1
  • 1
Viraj Pai
  • 205
  • 3
  • 11
  • 1
    switch is not necessarily faster than if/else - it depends on several factors, including the type of the switch variable (int vs String etc.), whether the case values are contiguous or not and how many cases there are. – assylias Mar 31 '14 at 13:50
  • Just a remark: are you sure you want to be optimizing at this level? This should be a last line of resort - when you have optimized everything else... Is your algorithm really at its best? Have you profiled your code to see if the bottlenecks are where you expect them? – Klaas van Gend Apr 01 '14 at 11:41

1 Answers1

9

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

Trenin
  • 2,041
  • 1
  • 14
  • 20