• Quick note - the problem with Youtube videos not embedding on the forum appears to have been fixed, thanks to ZiprHead. If you do still see problems let me know.

Switch vs If

Upchurch

Papa Funkosophy
Joined
May 10, 2002
Messages
34,265
Location
St. Louis, MO
What is better: Switch statements or If...Else If statements? And why?

I've heard from various sources give conflicting reports about which is faster and which is better for handling data. Personally, having come from a symbolic logic background, if...else if statements come much more natural to me, but I don't want to not use switch statements simply because I'm used to something else.

Opinions?
 
In my completely unprofessional opinion, I would minimise the use of if-else or switch so that it didn't matter which I used over the small number of options I was using it for.

Whenever I have ended up with a very large chunk of if-else code, unless it was for something trivial like parsing options from a command line, I ended up either refactoring to the strategy (or state) pattern, or I ploughed on regardless, and then bitterly regretted my decision shortly thereafter.

That assumes you're using an OO language, of course.
 
I realise I haven't answered your question at all. Sorry. I think in C, C++ and Java, the compiler can do some optimisations depending on how similar the int values are in the switch statement.

I certainly wish my coding was so efficient that this sort of thing was the bottleneck...
 
There shouldn't make any difference, I guess the compiler will output the same instructions either way. Look at this.
 
Well, as El Greco points out, processors only have conditional branch instructions, so a switch and an if-then will compile to roughly the same code.

Use whichever produces a cleaner and more readable program.
 
What is better: Switch statements or If...Else If statements? And why?

I've heard from various sources give conflicting reports about which is faster and which is better for handling data. Personally, having come from a symbolic logic background, if...else if statements come much more natural to me, but I don't want to not use switch statements simply because I'm used to something else.

Opinions?

I would not bother with what was faster unless there was a compelling hardware reason. Computers are here to work for us.
 
Well, as El Greco points out, processors only have conditional branch instructions, so a switch and an if-then will compile to roughly the same code.
Well, not necessarily. A compiler can convert a switch statement into an index address jump, making it effectively 1 operation to process the condition, as opposed to O(n/2) comparisons for if/else. With that said, I've rarely seen compilers generate that kind of code, though I have seen it. And of course, a really good optimizer could change the if/then into the equivelent if, gaining the same advantage.

More importantly, code your routine so it is readable as possible. Unless you are in a tight inner loop, the speed probably doesn't matter.
 
If it's important to the speed of the program, model it both ways and use the fastest. It's rarely that important to a program though.

I teach (I also debug what others have written) a specialized language for a plotting program for CAD software (InterPlot pen table language if you're really interested) and I've found for beginning script writers that extensive use of else if almost always results in a logic error, or is very unreadable and hard to debug.

samples below (i think the language is easy enough for most people to see what is going on)

Code:
if ((level_name == 'contours') and (color == 2)) then
  priority = 5
  color = 'light gray'
else if (color == 3) then
  priority = 10
  color = 'dark gray'
endif

There is a logic flaw in the above from what most users intend. The else if will trigger for all elements of color 3 no matter what. Most users mean for it to trigger when level_name is contours AND the color is 3. This is a very common mistake for new users.

Here's I usually write this
Code:
if (level_name == 'contours') then
  switch (color)
    case 2 ?
      priority = 5
      color = 'light gray'
    case 3 ?
       priority = 10
       color = 'dark gray'
  endswitch
endif

You'll notice that when properly indented the switch statments tend to line up the comparisons, while with else if's they tend to fall in the middle of a lot of text making them harder to find. Also the code for what is happening in each situation is indented more and makes following what is going on much easier.

Generally when I recommend on technique over the other it almost never comes down to which is faster and always comes down to which is easier to read, understand and maintain.

It takes a lot of executions for a 1/5 of a second improvement in execution time to make up for a 4 hour debugging session.

Oh and languages that require a break to get out a switch case, i hate those.
 
Last edited:
I wrote a virtual machine for a language once (neither one ended up getting implemented, but them's the breaks). Lots of fun tweaking the inner loop where it issued the opcodes and seeing the code produced by various compilers.

I tried using an array of function pointers, and it was faster - on some platforms - but caused problems with special cases. I ended up just using one big switch statement and relying on the optimiser to do all the hard work.
 
I tried using an array of function pointers, and it was faster - on some platforms - but caused problems with special cases. I ended up just using one big switch statement and relying on the optimiser to do all the hard work.

And in these days of frequent processor changes and software distribution by source (open or otherwise) and compiled for different processors, relying on compiler optimzation makes even more sense.

If you spent days on perfect hand optimization for a Pentium III processor, only to find the client is using AMD all that effort might be right down the drain.

Now if I were writing something for an embedded device I had control over all the hardware on, I might think differently. But I doubt it.
 
It depends: for example suppose you're doing an SQL call.
select clue from users where iq>100;
for some purpose a simple
if sqlcode = 0 then continue
else throw toys out

If you're doing something more important though you might want to:
switch (sqlcode)
case 0
continue
case +100
nosurprise = true
case -911
retry = true


etc etc.

Other times I choose one over the other
if (99.99% of cases) then continue
else figure out which of n other cases it is
That keeps the flow of "normal" processing uncluttered by code that only has to be invoked on rare occasions for special cases.

If there are more than 2 reasonably probable results I'll use switch or its equivalent. As has been said, make it easy for anyone reading the code to follow it.
 
Well, as El Greco points out, processors only have conditional branch instructions, so a switch and an if-then will compile to roughly the same code.

Not quite right.

Yes processors only have branching statements for control flow BUT they do not have to branch to a FIXED location as an IF statement might imply. The common optimisation for a switch statement is the use of a jump table to provide the branching destinations for the argument of the switch rather than a fall-through.

An array of function pointers as suggested is pretty much the right method (but there are far more efficient ways of storing such tables) but the main point I would emphasise is that you should definately structure your programs in such a way as that the logic is very clear and not try to do optimisations yourself. You will often just interfere with a compiler's attempts and compilers generally do a lot better than you ever will.

Use a switch statement for a task that is a switch. It's that simple really.

Oh and languages that require a break to get out a switch case, i hate those.

Then how exactly do these languages allow a fall-through?
 
...but the main point I would emphasise is that you should definately structure your programs in such a way as that the logic is very clear and not try to do optimisations yourself. You will often just interfere with a compiler's attempts and compilers generally do a lot better than you ever will.
This is the main sentiment I'm getting. It's not as satisfying as "Oh, switch/if statements are definitely and noticibly faster, you'd be a fool to use anything else", but I can accept that.
 
This is the main sentiment I'm getting. It's not as satisfying as "Oh, switch/if statements are definitely and noticibly faster, you'd be a fool to use anything else", but I can accept that.

When you come back to the code a year later, or have to fix somebody else's code who also held this sentiment, you will find it deeply satisfying. Especially when you have experienced the reverse. :boggled:
 
Rule of thumb I use in programming is, if it is an either/or then use if-else. Otherwise, use switch. Helps prevent nesting of ifs and, for Oracle at least, does perform slightly better.
 
Oh and languages that require a break to get out a switch case, i hate those.

Then how exactly do these languages allow a fall-through?

a) if/else have no fall through, why should switch
b) how useful is fall through? I've found it useful very rarely and can be coded for easily.
c) it makes debugging hard when left out.

Why make the rare case the default?
 
If you spent days on perfect hand optimization for a Pentium III processor, only to find the client is using AMD all that effort might be right down the drain.
Actually, that specific case is the only one that does work well. :) Optimising Athlon/Opteron and for Pentium Pro/II/III/M is much the same. The Pentium 4 is very different. Trying to get my code running fast on both Intel and PowerPC was fun, though.
 

Back
Top Bottom