Performance: switch or if aligned? [closed]

1

Regardless of language, switch performs better than aligning if s?

If yes: why?

if
  ...
elif
  ...
elif
  ...
else
  ...
end

switch
  case
    ...
  case
    ...
  case
    ...
  else
    ...
end
    
asked by anonymous 20.06.2014 / 16:02

1 answer

2
if a == 0
    ...
elsif a == 1
    ...
elsif a == 2
    ...
else
    ...
end

It is identical in semantics to:

switch a
case 0
    ...
case 1
    ...
case 2
    ...
default
    ...
end

So, a good tool will generate the same code or equivalent code in any measurable sense. If this is not true for your specific case (perhaps some feature of the language), then that case has to be seen in particular.

The only clear exception to the rule is if your a is not a simple expression, such as a variable read, but something complex that involves executing code. For example:

if prod.getProductType() == 50
    ...
elsif prod.getProductType() == 78
    ...
end

You can clearly run the function more than once, whereas in the case of the switch this would not happen. (Of course, an optimization might conclude that the function is pure and call only once, but that's not the case). If you need to do some computing to get the value you are going to test, better use switch. Otherwise, the two are equivalent. Use the one you find most readable.

One point to consider is that transforming a switch into a jump table is much easier to do than compiling from ifs. So if there are many cases and possibilities, it may be more advantageous to use a switch. Note that this also depends on the language.

    
20.06.2014 / 16:13