• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
bryan lim
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 42969
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
bryan lim
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65335
97
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
bryan lim
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you all. learn something again
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic