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

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

    I remember reading that there are 2 kinds of Switch statements in Java bytecode. (I think it was in 'Java Performance Tuning' One is a very fast implementation which uses the switch statement's integer values to know the offset of the code to be executed. This would require all integers to be consecutive and in a well-defined range. I'm guessing that using all the values of an Enum would fall in that category too.

    I agree with many other posters though... it may be premature to worry about this, unless this is very very hot code.

    0 讨论(0)
  • 2020-11-22 17:07

    According to Cliff Click in his 2009 Java One talk A Crash Course in Modern Hardware:

    Today, performance is dominated by patterns of memory access. Cache misses dominate – memory is the new disk. [Slide 65]

    You can get his full slides here.

    Cliff gives an example (finishing on Slide 30) showing that even with the CPU doing register-renaming, branch prediction, and speculative execution, it's only able to start 7 operations in 4 clock cycles before having to block due to two cache misses which take 300 clock cycles to return.

    So he says to speed up your program you shouldn't be looking at this sort of minor issue, but on larger ones such as whether you're making unnecessary data format conversions, such as converting "SOAP → XML → DOM → SQL → …" which "passes all the data through the cache".

    0 讨论(0)
提交回复
热议问题