This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes is Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "is "switch" statement more efficient than "if else" statement?" Watch "is "switch" statement more efficient than "if else" statement?" New topic
Author

is "switch" statement more efficient than "if else" statement?

bryan lim
Ranch Hand

Joined: Dec 26, 2008
Posts: 140
is "switch" statement more efficient than "if else" statement? if there is a switch with 1000 cases compared to 1000if else, which one is more efficient?
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 35237
    
    7
I'd say let the compiler and runtime worry about this. Even if there is a difference -and if there is one, the answer could differ between different versions of the JDK- this is not something you should base decisions on. What prompted this question?


Android appsImageJ pluginsJava web charts
bryan lim
Ranch Hand

Joined: Dec 26, 2008
Posts: 140
just a random question...

i did search google and they say switch is faster... but i also think that there is little difference....

so i really don need to bother about the efficiency here? is the efficiency difference really negligible?
Mohammed Amine Tazi
Greenhorn

Joined: Feb 09, 2009
Posts: 22
It's simple Performance depends on the breaking condition. I think that if else and switch have the same performance if the breaking condition is in the same level. In order to test that, let's have a 1000 times loop and an if condition. The same test using switch. But don't forget to output the entering and exiting method timestamp to get the timing. You'll see that performance is the same.


SCJP 5 / SCWCD 5 / SCBCD 5 / SCDJWS 4 / SCDJWS 5 / SCEA 5
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 56180
    
  13

The most important thing to remember is to code your code for clarity. Minor differences in performance are moot. It's only when gross inefficiencies are detected that you should consider optimizing your code with the aid of profiler to exactly pinpoint where bottlenecks may lie.


[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About Bear]
bryan lim
Ranch Hand

Joined: Dec 26, 2008
Posts: 140
thank you all. learn something again
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: is "switch" statement more efficient than "if else" statement?
 
Similar Threads
Switch Statements
Does Java have an equivalent of a COBOL Evaluate Statement?
switch case v/s if else
Difference Between Switch and if else
The switch statement