Possible Duplicates:
is “else if” faster than “switch() case” ?
What is the relative performance of if/else vs. switch in Java?
Ive been coding-in-the-run again....when the debugger steps through a case statement it jumps to the item that matches the conditions immediately, however when the same logic is specified using if/else it steps through every if statement until it finds the winner. Is the case statement more efficient, or is my debugger just optimizing the step through? (don't worry about the syntax/errors, i typed this in SO, don't know if it will compile, its the principle i'm after, I didn't want to do them as ints cause i vaguely remember something about case using an offset with ints) I use C#, but im interested in a general answer across programming languages.
switch(myObject.GetType()){ case typeof(Car): //do something break; case typeof(Bike): //do something break; case typeof(Unicycle): //do something break; case default: break; }
VS
Type myType = myObject.GetType(); if (myType == typeof(Car)){ //do something } else if (myType == typeof(Bike)){ //do something } else if (myType == typeof(Unicycle)){ //do something } else{ }
Furthermore ELSE IF is more efficient because the computer only has to check conditions until it finds a condition that returns the value TRUE. By using multiple IF-conditions the computer has to go through each and every condition and thus multiple IF-conditions require more time.
Speed: A switch statement might prove to be faster than ifs provided number of cases are good. If there are only few cases, it might not effect the speed in any case. Prefer switch if the number of cases are more than 5 otherwise, you may use if-else too.
A switch statement works much faster than an equivalent if-else ladder. It's because the compiler generates a jump table for a switch during compilation. As a result, during execution, instead of checking which case is satisfied, it only decides which case has to be executed.
If-else statement takes a specific condition and checks whether the condition is truthy or falsy. If the condition is true, then the if statement executes a specific code block. If the condition is false, then the else statement executes a different code block. Let's take a simple example to understand how this works.
It seems that the compiler is better in optimizing a switch-statement than an if-statement.
The compiler doesn't know if the order of evaluating the if-statements is important to you, and can't perform any optimizations there. You could be calling methods in the if-statements, influencing variables. With the switch-statement it knows that all clauses can be evaluated at the same time and can put them in whatever order is most efficient.
Here's a small comparison:
http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With