is "switch" statement more efficient than "if else" statement?
bryan lim
Ranch Hand
Joined: Dec 26, 2008
Posts: 140
posted
0
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: 35252
7
posted
0
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?
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
posted
0
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.
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.