Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Which is faster if-else or Switch case ?

Status
Not open for further replies.

D KARTHICK

Programmer
Oct 6, 2018
1
IN
Which is faster if-else or Switch case ?
 
Depends on what you are doing - sometimes, it can be solved by simple arithmetic, which is faster than both. What exactly are you trying to do?

For example, if a number is 5, make it 2, if it is 2, make it 5. It could be coded as
Code:
' if statement - assuming it will only ever be 2 or 5
if x = 5 then
    x = 2
else
    x = 5
end if

' arithmetic - assuming it will only ever be 2 or 5
x = 7 - x
 
Technically, a Switch / Case statement is faster because in an IF Statment, each IF / ElseIF is evaluated. In a Switch/Case, once the condition is met, the Switch/Case is exited.
Personally, I find Switch/Case to look cleaner and more readable as well. If it is just a small check as in xwb's example, then I would just use a standard IF or to shorten it I would use an InLine IF. The syntax differs between VB and C#
 
It really depends on the internal implementation of the switch statement.

If the cases are sequential, very often, the implementation is the equivalent of a computed goto. For example
Code:
    switch (x)
    {
    case 8: ...; break;
    case 5: ...; break;
    case 7: ...; break;
    case 6: ...; break;
    }
The compiler would arrange them as 5, 6, 7,8, subtract 5 from x and use a computed goto.

If the cases are not sequential, they could be sorted into a lookup table followed by a computed goto. Alternatively, it could be implemented as an if-elseif-else statement. If it is the latter then there is no difference between the switch and the if-elseif-else other than possibly elegance of the code.
 
An IF statement will always evaluate each condition. A switch will fall through once the condition is met. True, depending on the conditions, they could be equal in performance, but the switch will win out in most cases.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top