Is else if faster than switch() case?
For just a few items, the difference is small. If you have many items you should definitely use a switch.
If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if:s where the last item takes much more time to reach as it has to evaluate every previous condition first.
If vs. Switch Speed
The compiler can build jump tables where applicable. For example, when you use the reflector to look at the code produced, you will see that for huge switches on strings, the compiler will actually generate code that uses a hash table to dispatch these. The hash table uses the strings as keys and delegates to the case
codes as values.
This has asymptotic better runtime than lots of chained if
tests and is actually faster even for relatively few strings.
Which is Faster and better, Switch Case or if else if?
Your first example is simply wrong. You need elseif
instead of just else
.
If you use if..elseif...
or switch
is mainly a matter of preference. The performance is the same.
However, if all your conditions are of the type x == value
with x
being the same in every condition, switch
usually makes sense. I'd also only use switch
if there are more than e.g. two conditions.
A case where switch
actually gives you a performance advantage is if the variable part is a function call:
switch(some_func()) {
case 1: ... break;
case 2: ... break;
}
Then some_func()
is only called once while with
if(some_func() == 1) {}
elseif(some_func() == 2) {}
it would be called twice - including possible side-effects of the function call happening twice. However, you could always use $res = some_func();
and then use $res
in your if
conditions - so you can avoid this problem alltogether.
A case where you cannot use switch at all is when you have more complex conditions - switch
only works for x == y
with y
being a constant value.
if else vs switch performance in java
Switch
perf is better than if else
as in case of switch there will be one time evaluation . Once it evaluated the switch it knows which case needs to be executed but in case of if else
it has to go through all conditions in case of worst scenario.
The longer the list condition, better will be switch performance but for shorter list (just two conditions), it can be slower also
From Why switch is faster than if
With switch the JVM loads the value to compare and iterates through
the value table to find a match, which is faster in most cases
What is the relative performance difference of if/else versus switch statement in Java?
That's micro optimization and premature optimization, which are evil. Rather worry about readabililty and maintainability of the code in question. If there are more than two if/else
blocks glued together or its size is unpredictable, then you may highly consider a switch
statement.
Alternatively, you can also grab Polymorphism. First create some interface:
public interface Action {
void execute(String input);
}
And get hold of all implementations in some Map
. You can do this either statically or dynamically:
Map<String, Action> actions = new HashMap<String, Action>();
Finally replace the if/else
or switch
by something like this (leaving trivial checks like nullpointers aside):
actions.get(name).execute(input);
It might be microslower than if/else
or switch
, but the code is at least far better maintainable.
As you're talking about webapplications, you can make use of HttpServletRequest#getPathInfo()
as action key (eventually write some more code to split the last part of pathinfo away in a loop until an action is found). You can find here similar answers:
- Using a custom Servlet oriented framework, too many servlets, is this an issue
- Java Front Controller
If you're worrying about Java EE webapplication performance in general, then you may find this article useful as well. There are other areas which gives a much more performance gain than only (micro)optimizing the raw Java code.
Is 'switch' faster than 'if'?
There are several optimizations a compiler can make on a switch. I don't think the oft-mentioned "jump-table" is a very useful one though, as it only works when the input can be bounded some way.
C Pseudocode for a "jump table" would be something like this -- note that the compiler in practice would need to insert some form of if test around the table to ensure that the input was valid in the table. Note also that it only works in the specific case that the input is a run of consecutive numbers.
If the number of branches in a switch is extremely large, a compiler can do things like using binary search on the values of the switch, which (in my mind) would be a much more useful optimization, as it does significantly increase performance in some scenarios, is as general as a switch is, and does not result in greater generated code size. But to see that, your test code would need a LOT more branches to see any difference.
To answer your specific questions:
Clang generates one that looks like this:
test_switch(char): # @test_switch(char)
movl %edi, %eax
cmpl $19, %edi
jbe .LBB0_1
retq
.LBB0_1:
jmpq *.LJTI0_0(,%rax,8)
jmp void call<0u>() # TAILCALL
jmp void call<1u>() # TAILCALL
jmp void call<2u>() # TAILCALL
jmp void call<3u>() # TAILCALL
jmp void call<4u>() # TAILCALL
jmp void call<5u>() # TAILCALL
jmp void call<6u>() # TAILCALL
jmp void call<7u>() # TAILCALL
jmp void call<8u>() # TAILCALL
jmp void call<9u>() # TAILCALL
jmp void call<10u>() # TAILCALL
jmp void call<11u>() # TAILCALL
jmp void call<12u>() # TAILCALL
jmp void call<13u>() # TAILCALL
jmp void call<14u>() # TAILCALL
jmp void call<15u>() # TAILCALL
jmp void call<16u>() # TAILCALL
jmp void call<17u>() # TAILCALL
jmp void call<18u>() # TAILCALL
jmp void call<19u>() # TAILCALL
.LJTI0_0:
.quad .LBB0_2
.quad .LBB0_3
.quad .LBB0_4
.quad .LBB0_5
.quad .LBB0_6
.quad .LBB0_7
.quad .LBB0_8
.quad .LBB0_9
.quad .LBB0_10
.quad .LBB0_11
.quad .LBB0_12
.quad .LBB0_13
.quad .LBB0_14
.quad .LBB0_15
.quad .LBB0_16
.quad .LBB0_17
.quad .LBB0_18
.quad .LBB0_19
.quad .LBB0_20
.quad .LBB0_21I can say that it is not using a jump table -- 4 comparison instructions are clearly visible:
13FE81C51 cmp qword ptr [rsp+30h],1
13FE81C57 je testSwitch+73h (13FE81C73h)
13FE81C59 cmp qword ptr [rsp+30h],2
13FE81C5F je testSwitch+87h (13FE81C87h)
13FE81C61 cmp qword ptr [rsp+30h],3
13FE81C67 je testSwitch+9Bh (13FE81C9Bh)
13FE81C69 cmp qword ptr [rsp+30h],4
13FE81C6F je testSwitch+0AFh (13FE81CAFh)A jump table based solution does not use comparison at all.
- Either not enough branches to cause the compiler to generate a jump table, or your compiler simply doesn't generate them. I'm not sure which.
EDIT 2014: There has been some discussion elsewhere from people familiar with the LLVM optimizer saying that the jump table optimization can be important in many scenarios; e.g. in cases where there is an enumeration with many values and many cases against values in said enumeration. That said, I stand by what I said above in 2011 -- too often I see people thinking "if I make it a switch, it'll be the same time no matter how many cases I have" -- and that's completely false. Even with a jump table you get the indirect jump cost and you pay for entries in the table for each case; and memory bandwidth is a Big Deal on modern hardware.
Write code for readability. Any compiler worth its salt is going to see an if / else if ladder and transform it into equivalent switch or vice versa if it would be faster to do so.
Switch vs If-Else Performance
I wrote this test to check if I could figure out which way is better using Measure-Command
:
function switchtest {
param($name)
switch -Regex ($name) {
$optionsarray[0] {
Write-host $name
break
}
$optionsarray[1] {
Write-host $name
break
}
$optionsarray[2] {
Write-host $name
break
}
$optionsarray[3] {
Write-host $name
break
}
$optionsarray[4] {
Write-host $name
break
}
default { }
}
}
function iftest {
param($name)
If ($name -match $optionsarray[0]) {Write-host $name}
ElseIf ($name -match $optionsarray[1]) {Write-host $name}
ElseIf($name -match $optionsarray[2]) {Write-host $name}
ElseIf($name -match $optionsarray[3]) {Write-host $name}
ElseIf($name -match $optionsarray[4]) {Write-host $name}
}
$optionsarray = @('Joe Bloggs', 'Blog Joggs', 'Steve Bloggs', 'Joe Jobs', 'Steve Joggs')
for ($i=0; $i -lt 10000; $i++) {
$iftime = 0
$switchtime = 0
$rand = Get-Random -Minimum 0 -Maximum 4
$name = $optionsarray[$rand]
$iftime = (Measure-Command {iftest $name}).Ticks
$switchtime = (Measure-Command {switchtest $name}).Ticks
Add-Content -Path C:\path\to\outfile\timetest.txt -Value "$switchtime`t$iftime"
}
Results
On average, this is how each function performed in 10,000 tests:
Switch - 11592.8566
IfElse - 15740.3281
The results were not the most consistent (sometimes switch
was faster, sometimes ifelse
was faster) but as switch
is faster overall (on mean average) I will be using this instead of ifelse
.
Would appreciate any feedback on this decision and my testing.
Case vs If Else If: Which is more efficient?
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
Switch statement vs if statement, which is better for performance?
Switch may (depending on the implementatin) use jump table (in c and c++), so under certain conditions it may be more performant. Generally, it states your intention more clear so compiler can pretend it's smart.
considering if
in your example doesn't even use else if
chain, it makes switch
even faster (because of not evaluating all conditions) and also may change the meaning of your code (in case your dothises modify x
).
Why switch is faster than if
Because there are special bytecodes that allow efficient switch statement evaluation when there are a lot of cases.
If implemented with IF-statements you would have a check, a jump to the next clause, a check, a jump to the next clause and so on. With switch the JVM loads the value to compare and iterates through the value table to find a match, which is faster in most cases.
Related Topics
How to Use the Paint Event to Draw Shapes at Mouse Coordinates
When Is It Appropriate to Use C# Partial Classes
When Should Taskcompletionsource<T> Be Used
C#: Printing All Properties of an Object
Are Static Class Instances Unique to a Request or a Server in ASP.NET
Differencebetween "X Is Null" and "X == Null"
Get Controller and Action Name from Within Controller
Which Version of C# am I Using
Using a Self-Signed Certificate with .Net's Httpwebrequest/Response
Token Based Authentication in Web API Without Any User Interface
Server Client Send/Receive Simple Text
What Is More Efficient: Dictionary Trygetvalue or Containskey+Item
Httpclient - a Task Was Cancelled
Mvc3 Razor Dropdownlistfor Enums
Sending Arguments to Background Worker