aspose file tools*
The moose likes Performance and the fly likes Switch..Case Vs If..Else Performance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Performance
Bookmark "Switch..Case Vs If..Else Performance" Watch "Switch..Case Vs If..Else Performance" New topic
Author

Switch..Case Vs If..Else Performance

Dhandapani Venkataraman
Greenhorn

Joined: Nov 30, 2003
Posts: 10
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

"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.


[Jess in Action][AskingGoodQuestions]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Note that there is a third alternative that is often both faster and more flexible: polymorphism.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
wood burning stoves
 
subject: Switch..Case Vs If..Else Performance