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

前端 未结 8 1326
北恋
北恋 2020-11-22 16:25

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

8条回答
  •  [愿得一人]
    2020-11-22 16:55

    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 actions = new HashMap();
    

    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.

提交回复
热议问题