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

前端 未结 8 1220
北恋
北恋 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 17:05

    It's extremely unlikely that an if/else or a switch is going to be the source of your performance woes. If you're having performance problems, you should do a performance profiling analysis first to determine where the slow spots are. Premature optimization is the root of all evil!

    Nevertheless, it's possible to talk about the relative performance of switch vs. if/else with the Java compiler optimizations. First note that in Java, switch statements operate on a very limited domain -- integers. In general, you can view a switch statement as follows:

    switch () {
       case c_0: ...
       case c_1: ...
       ...
       case c_n: ...
       default: ...
    }
    

    where c_0, c_1, ..., and c_N are integral numbers that are targets of the switch statement, and must resolve to an integer expression.

    • If this set is "dense" -- that is, (max(ci) + 1 - min(ci)) / n > α, where 0 < k < α < 1, where k is larger than some empirical value, a jump table can be generated, which is highly efficient.

    • If this set is not very dense, but n >= β, a binary search tree can find the target in O(2 * log(n)) which is still efficient too.

    For all other cases, a switch statement is exactly as efficient as the equivalent series of if/else statements. The precise values of α and β depend on a number of factors and are determined by the compiler's code-optimization module.

    Finally, of course, if the domain of is not the integers, a switch statement is completely useless.

提交回复
热议问题