I was wondering, if we have if-else
condition, then what is computationally more efficient to check: using the equal to operator or the not equal to operator? Is there any difference at all?
E.g., which one of the following is computationally efficient, both cases below will do same thing, but which one is better (if there's any difference)?
Case1:
if (a == x)
{
// execute Set1 of statements
}
else
{
// execute Set2 of statements
}
Case 2:
if (a != x)
{
// execute Set2 of statements
}
else
{
// execute Set1 of statements
}
Here assumptions are most of the time (say 90% of the cases) a
will be equal to x
. a
and x
both are of unsigned integer type.
What I meant is that the CPU could detect two values are not equal without looking at all bits, but it doesn't matter whether you use == or != to find that they are not equal, so the two operators are exactly equivalent. There is no reason to think one is faster than the other.
The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .
If the values compared are not equal, then a value of false is returned. != is the symbol we use for the not equal operator.
Python not equal operator returns True if two variables are of same type and have different values, if the values are same then it returns False . Python is dynamic and strongly typed language, so if the two variables have the same values but they are of different type, then not equal operator will return True .
Generally it shouldn't matter for performance which operator you use. However it is recommended for branching that the most likely outcome of the if-statement comes first.
Usually what you should consider is; what is the simplest and clearest way to write this code? IMHO, the first, positive is the simplest (not requiring a !)
In terms of performance there is no differences as the code is likely to compile to the same thing. (Certainly in the JIT for Java it should)
For Java, the JIT can optimise the code so the most common branch is preferred by the branch prediction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With