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

前端 未结 8 1201
北恋
北恋 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:44

    For most switch and most if-then-else blocks, I can't imagine that there are any appreciable or significant performance related concerns.

    But here's the thing: if you're using a switch block, its very use suggests that you're switching on a value taken from a set of constants known at compile time. In this case, you really shouldn't be using switch statements at all if you can use an enum with constant-specific methods.

    Compared to a switch statement, an enum provides better type safety and code that is easier to maintain. Enums can be designed so that if a constant is added to the set of constants, your code won't compile without providing a constant-specific method for the new value. On the other hand, forgetting to add a new case to a switch block can sometimes only be caught at run time if you're lucky enough to have set your block up to throw an exception.

    Performance between switch and an enum constant-specific method should not be significantly different, but the latter is more readable, safer, and easier to maintain.

提交回复
热议问题