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.
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
Which is better a switch statement or if-else if-else statement?
The compiler can create a jump table for certain types of switch statements which is more efficient than just evaluating each element like a nested set of if statements. This is dependent on the type of switch and the language you are working in, but many C compilers just this sort of thing in their code generation.
So the short is that a switch can be more efficient but it depends on your particular usage.
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
Is there any performance gain from using a switch statement over a bunch of if()else if() in javascript?
In general, switch
is faster than if - else if
statements.
However, kind of best practice is to use if - else if
if you got max 3 conditionals. If you're going beyond that, you should use switch
statements.
The problem with if else
is that it possibly needs to check multiple times before it finally reaches the code to execute. Therefore you also need to optimize the order for your conditional statements.
if( foo ) {
}
else if( bar ) {
}
else if( baz ) {
}
That code would not make much sense from a performance prospective if you expect baz
to be true
and foo
/bar
to be false
most of the times.
Is there a difference in the operations of if/else and a switch statement?
if your case more than four, switch-case statement is more effiecient. your case directly jumped. on the other hand if you use if-else statement all cases compared until your cases is crossed.
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.
Java switch statement with two cases or if statement?
The answer is really depends on the interest of usage. What usually I do is, If my conditions are more (3 or above) I'l go for switch. Otherwise I simply use if-else-if
.
Java switch statement with two cases or if statement?
For your case the first is good enough which is if else. If there are more cases like that, prefer switch. That increases readability versus ugly good amount of if else's
.
Related Topics
How to Use a Custom Serializer with Jackson
Map Implementation with Duplicate Keys
Java Reading a File into an Arraylist
How to Switch to the New Browser Window, Which Opens After Click on the Button
Parse String to Date with Different Format in Java
How to Execute Cmd Commands via Java
How to Merge Two Sorted Arrays into a Sorted Array
How to Get Current Moment in Iso 8601 Format with Date, Hour, and Minute
How to Catch an Exception from a Thread
Should a Retrieval Method Return 'Null' or Throw an Exception When It Can't Produce the Return Value
Java Regex Meta Character (.) and Ordinary Dot
How to Reference Javafx Fxml Files in Resource Folder