File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes is Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
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: 39537
    
  27
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?


Ping & DNS - updated with new look and Ping home screen widget
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: 60046
    
  65

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.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
bryan lim
Ranch Hand

Joined: Dec 26, 2008
Posts: 140
thank you all. learn something again
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: is "switch" statement more efficient than "if else" statement?
 
Similar Threads
Switch Statements
switch case v/s if else
Does Java have an equivalent of a COBOL Evaluate Statement?
The switch statement
Difference Between Switch and if else