Java: Performance of Enums vs. if-then-else

后端 未结 6 1744

I\'ve had no real luck getting a concise answer for this comparison by using Google and rather than do my own time consuming evaluations, I thought I would ask first.

<
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 21:03

    Yes, a switch statement will pretty much always execute faster than the equivalent block of if / else statements because the compiler can perform more optimisations (typically a switch block becomes compiled down to a branch table which is pretty much impossible to do with a block of conditionals.)

    I'd say they're also both more readable and more maintainable (with the exception of using fall-through cases which I'd advise against!)

    As to whether it's noticeably faster, it depends what you define as noticeable. Chances are unless you're after something really specific you won't notice it at all, but I'd still do things this way because of the readability advantage more than anything else (treat the speed advantage as a bonus!)

提交回复
热议问题