which makes faster code? if's or switch?

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.
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?
how about, switch vs if else if ladders?
closed account (Dy7SLyTq)
isnt there already a test library for this out there?
Using a switch will probably be at least as fast as using ifs.
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.
closed account (Dy7SLyTq)
no i know they exist, but i dont know if there is a specific test for if/switch
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.
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.
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
If choices are more like more than 2 go for switch-case. Its faster...
Topic archived. No new replies allowed.