Reputation: 1729
This has been bugging me for a while and I'm not sure if there is a correct answer:
Take these two statements
if(foo == bar)
do this;
else if(foo != bar)
do that;
or
if(foo != bar)
do that;
else if(foo == bar)
do this;
which one of these is correct (forgetting optimization for now) My mind tells me that the answer depends on what result is expected for example if this was running in a loop and I predicted that foo will be equal to bar more times than it is not then the first one would be correct.
Is there any efficiency implications between the notations?
Upvotes: 3
Views: 164
Reputation: 86296
If I understand correctly, you are asking about the difference between the following two snippets.
if (predicate1()) {
doThis();
} else if (predicate2()) {
doThat();
}
if (predicate2()) {
doThat();
} else if (predicate1()) {
doThis();
}
If predicate1 and predicate2 may both be true at the same time, there is a difference in the outcome, I am sure you are aware of that. So I will assume that at most one of them can be true. I am also assuming that we can safely ignore any side effects from evaluating the conditions.
Is there a readability difference? Not as the code stands. However, in a concrete situation it could well be that the average reader will find it more natural to evaluate one predicate first. If so, go by that.
You ask about efficiency. First answer is, you shouldn’t. But anyway, there are two guidelines, and I think you have touched on both already:
If we had numbers, we could make a fine piece of math calculating the average cost of each snippet and choose the best.
As to whether ==
or !=
is cheaper, with my attitude I obviously don’t know the answer. I would expect it to vary with the types you compare, with whether you are running byte code or native code, with your type of CPU and other factors. You may go measure, and there may be folks around that know a rule thumb or two. In any case, the difference has to be very minute.
Upvotes: 1
Reputation: 189
Why not just do this
if(foo == bar)
do this;
else
do that;
Seems clearer that way, and if you are returning any statements inside the conditional blocks, it makes the program more readable
Upvotes: 1
Reputation: 923
If you dont want to go for If...else condition , you can use ternary operator .
like result = testStatement ? value1 : value2;
But for nested conditions , ternary operator looks very complex.
Upvotes: 2
Reputation: 13
It really does make much of a difference, optimisation wise. It comes down to your style and preferences. Both of your examples have the same impact.
Upvotes: 1
Reputation: 201447
But is there any efficiency implications between the notations? No. None at all. Prefer the one that is most readable. If it reads better saying "if not a
" in a sentence, use !
. Otherwise, don't.
Upvotes: 5