• Post Reply Bookmark Topic Watch Topic
  • New Topic

The switch statement  RSS feed

 
Rahul Sudip Bose
Ranch Hand
Posts: 637
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) Why does it accept ONLY compile time constants ?
2) Is it EXACTLY like multiple if-else checks ?
Consider an eg. switch gets int 9. cases are 3 to 15. Does the switch compare 7 with each int from 3 to 9 ? Or does it do something else ?
3) Which is faster : many if-else or switch ? How to measure that speed ? Is that measurement of any practical value ?

< I have strong doubts if we can measure it correctly, because the processor has so many things to do besides the if-else/switch. All the time for those activities might affect our values.
Can we tell the processor - NOW, GO ONLY THROUGH THE IF-ELSE TILL ITS END (WHILE A STOPWATCH MEASURES THE TIME). Any thoughts on this ? >
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason why it accepts only compile-time constants has to do with how the switch statement works under the covers. It enables the Java compiler and JIT to implement the switch via a branch table. The constants must be known at compile time for the compiler to be able to set up the branch table.

Logically, it does the same as multiple if ... else if ... statements. Under the covers, it doesn't work in the same way. A switch statement is probably more efficient than a chain of if ... else if ... statements.

I wouldn't try to force my code into a switch statement just because I suspect that it is faster - that's premature optimization.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!