Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Switch..Case Vs If..Else Performance

 
Dhandapani Venkataraman
Greenhorn
Posts: 10
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there any unambiguos proof or statement in the Java specification that says how switch..case evaluation is done internally by the JVM? Is it always true that switch .. case executes faster than an equivalent if..else structure?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"switch" corresponds to two different bytecode instructions named "tableswitch" and "lookupswitch". "tableswitch" is used for contiguous cases without gaps, while the slower "lookupswitch" is used for more spread-out values.

There is absolutely nothing in the JLS or VM Spec about the relative speeds of switch vs if/else, nor is there any hard and fast rule; nor could you make such a general statement based on empirical evidence. Which is faster will depend on many factors. Write the clearest, best-designed code you can, and let HotSpot worry about these micro-efficiency issues.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that there is a third alternative that is often both faster and more flexible: polymorphism.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic