which makes faster code? if's or switch?

Mar 10, 2013 at 11:47pm
I have a lot of things to test for I need to know which makes faster executing code. Compile time is unimportant.
A bunch of ifs or a huge switch case.
Mar 10, 2013 at 11:55pm
Depends on the kind of conditions and your optimizer. Usually a switch statement is faster than consecutive if-statements.

But you may wright some test program and measure times yourself?
Mar 11, 2013 at 2:03am
@tcs
how about, switch vs if else if ladders?
Mar 11, 2013 at 2:04am
closed account (Dy7SLyTq)
isnt there already a test library for this out there?
Mar 11, 2013 at 9:13am
Using a switch will probably be at least as fast as using ifs.
Mar 11, 2013 at 9:34am
I don't know whether there exists such tools/libraries for time measurements. But it should be not as difficult to write down some test program yourself in a few minutes:

1. Start a timer (f.e. use times(2)).
2. Following lines will be your test. F.e. an if-else statements of 10 conditions. Select f.e. the last condition.
3. Repeat step 2. f.e. 1000000 times.
4. Stop the timer.
5. Build the average of your measured time and the number of cycles.

If you use times(2) starting/stoping the timer is nothing else then just measuring current time while step 5. builds the average of the difference of both measurements and the number of cycles.

See manual pages for more infos.

Good luck.
Mar 11, 2013 at 7:52pm
closed account (Dy7SLyTq)
no i know they exist, but i dont know if there is a specific test for if/switch
Mar 12, 2013 at 11:56pm
If you are using GCC, use -S option to see switch and if else blocks in assembly language.
Then check which one is more verbose. usually verbose code in assembly language takes more time.
Mar 13, 2013 at 2:04am
In comes down to whether your cases are dense (consecutive) or sparse. If the cases are dense, most compilers will generate a jump table which is very efficient. If the cases are sparse, the compiler will generate an if/else ladder which will probably be a wash.
Mar 13, 2013 at 2:46am
Hmmmm it depends about your program field, means if your program in data entry field then you should consider those formulas in sorting, saving, modifying...

and since life is going forward! >>>>>>>>>>>>>>> compilers are more smarter than before!, check optimizing out :)
Last edited on Mar 13, 2013 at 2:47am
Mar 13, 2013 at 6:54am
If choices are more like more than 2 go for switch-case. Its faster...
Topic archived. No new replies allowed.