• Post Reply Bookmark Topic Watch Topic
  • New Topic

which is faster Switch Or If else stetment.  RSS feed

 
Omkar G. Deshmukh
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which statements executes fastly switch or if else.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Omkar G. Deshmukh wrote:Which statements executes fastly switch or if else.

Simple answer: Don't know - and I wouldn't trust any other answer you get, because it might be different on different machines or JVMs.

Personally, I usually find switch statements easier to read - and that's generally the only criterion that's worth worrying about. On the flip side, switch statements are also easier to get wrong.

Both are likely to be measured in nanoseconds, and speed is the last thing you should normally be thinking about when you're programming - at least until you actually find you have a problem.

Get it right. Then, if you need to - and ONLY if you need to - make it fast.

It's also probably worth mentioning that there are many situations where you can't use switch, so you won't have any choice in the matter.

Winston
 
Junilu Lacar
Sheriff
Posts: 11477
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's a corollary to your tagline: "Many mistakes come from trying to get the wrong thing right." -- Me (as far as I know)
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can't imagine either would be significantly faster, but let us assume one is - doesn't matter which.

If you use the slower method, and it takes 1/1000th of a second longer to run (which is an ETERNITY in computing time), you would have to run through that specific section of code 1000 times before you save ONE SECOND. Odds are pretty good that with everything else going on, nobody will notice that.

Now, if you have to debug your code, you want it to be as EASY as possible to understand. Writing code that saves you an hour of debug time is VASTLY more valuable that writing code that saves a user 1/1000th of a second.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

As many ranchers already mentioned -- assuming that it is even important (compared to other parts of the application), you have to test it. Make sure that is an issue before you go about trying to optimize it.


Having said that, the design of if-then statements are very different from the design of switch-case statements. Switch-case statements are supposed to know the targets at compile time (case targets are compile time constants). And because of this, it can be implemented as a jump-table. This means that even with hundreds of case statements, evaluation and getting to the case target should be very similar in latency (or arguably, very difficult to measure).

On the other hand, if-then statements must evaluate expressions as it go through the different conditionals. This gives it a ton more flexibility in terms of branching logic -- heck, it can use anything to determine the branch. However, because of this, with hundreds of if-then-if-then blocks, the first block has a lower latency to reach its target code block than the later ones. And if the conditional expression is really slow, such as needing to go through a database, the difference between the first block and the last block can be dramatic.


As for which is faster? As mentioned, if it is important, test it. However, I think it is safe to assume that with lots of case statements, the switch statement to reach its case block may be faster than the average for the if-then statement to reach its target block.

Henry
 
Ulf Lindqvist
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Omkar G. Deshmukh wrote:
Which statements executes fastly switch or if else.


You should use a switch when the probablity of each choise is (roughly) the same.

Otherwise use an if-else chain with the choises in order of probability (with the most probable choise first).

If you have no idea how likely the choises are use a switch because it's nicer on the eye.

 
Ulf Lindqvist
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston Gutkowski wrote:
Simple answer: Don't know - and I wouldn't trust any other answer you get, because it might be different on different machines or JVMs.


You're wrong because the "probability of choises" criterion I mention in my previous reply is implementation independent.
 
drac yang
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is a complex question and it has many situations for comparison.

if we make it in the simplest form like just comparing the fowllowing two:

switch(intVariable) {
case: someConstant
doSomething();
break;
}

if(intVariable==someConstant) {
doSomething();
}

in this simple and direct situation, i think the latter is more probable to be faster(fewer clauses to be executed from vision, let's just assume no heavy optimization has been made under the hood)
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ulf Lindqvist wrote:You're wrong because the "probability of choises" criterion I mention in my previous reply is implementation independent.

I'm not "wrong" unless you can:
(a) Point me to the relevant paragraph in the JLS or JVM spec that specifies HOW a switch statement is executed.
(b) Convince me that the choice of if over switch - even when probabilities are not uniform - is so overwhelming that it overrides the many other concerns already mentioned.

Your statement also only makes sense if you take into account the length of time it takes to evaluate each test expression and order by probability products - and do you really want to do that? I suspect also that for some varieties of test and a good optimizing compiler, switch might only ever need to evaluate the test condition once, whereas an if stack is far more likely to need to evaluate each case in turn.

Winston
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also consider how the number of possible choices affects the design decision.

For example I use switch in "state machine" type applications where an user might be in 8 or more possible states. The current state was calculated at the end of the last state, so no new computation was required.

Using if-else-then for 8 different int comparisons would create a ghastly mess.


Bill
 
Jayesh A Lalwani
Rancher
Posts: 2762
32
Eclipse IDE Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ulf Lindqvist wrote:
Winston Gutkowski wrote:
Simple answer: Don't know - and I wouldn't trust any other answer you get, because it might be different on different machines or JVMs.


You're wrong because the "probability of choises" criterion I mention in my previous reply is implementation independent.


Actually, no you are wrong. I ran this unit test. Both methods generates a number between 1 and 3, with 1 having 60% probablilty, 2 having 30% and 1 having 10 percent. One method check the value in an if statement in decreasing order of probability. The other test has a switch statement in decreasing order of probability.


Both tests run in almost the same time. The differrence is hardly 1%, and the testIf is consistently slower than testSwitch. This is mainly because the testId runs a comparison 3 times, whereas switch probably does it one operation. However, like Winston said, this is highly dependent on the JVM, and actually the OS and even the CPU.

Going back to my C++ days, when we used to dicker about minute details on performance a lot, the general consensus was that switch statement is generally faster than If because generally the compiler generates machine code that uses something called a jump table. This makes the CPU to jump to a particular line of machine instruction faster, whereas an if-else chain would be translated into a a series of jumps. However this is a big caveat because it was compiler depdendent. A compiler can easily "implement" a switch statement as a if-else chain. THis is even more true when you get the JVM into the mix. You just don;t know how the JVM will interpret the byte code for a switch statement. It might interpret it into a if-else-chain or it might use a jump table. If you have an if-else chain, the JVM might figure out that the comparisons inside the if can be done with a switch, and it might just revert to using a switch all by itself.

The point is that you don't know... and you shouldn't know. This kind of hyperoptimizatin leads to messy code. Believe me, I've done it, got a tshirt that got burned when the project burned down. Premature optimization is the root of all evil. In the long run an 1% gain is not going to give you much. Clarity of code is going to give you a lot more.
 
Junilu Lacar
Sheriff
Posts: 11477
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jayesh A Lalwani wrote:Premature optimization is the root of all evil. In the long run an 1% gain is not going to give you much. Clarity of code is going to give you a lot more.

Amen to that.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!