Search code examples
javaperformanceswitch-statementif-statement

What is the relative performance difference of if/else versus switch statement in Java?


Worrying about my web application's performances, I am wondering which of "if/else" or switch statement is better regarding performance?


Solution

  • 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:

    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.