Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is efficient to check: equal to or not equal to?

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.

like image 447
jsist Avatar asked Dec 12 '12 12:12

jsist


People also ask

Is != Slower than ==?

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.

What is the relative operator for not equal to?

The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .

What is the comparison operator symbol for not equal to?

If the values compared are not equal, then a value of false is returned. != is the symbol we use for the not equal operator.

What is not equal operator in python?

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 .


2 Answers

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.

like image 110
Crog Avatar answered Nov 07 '22 13:11

Crog


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.

like image 35
Peter Lawrey Avatar answered Nov 07 '22 11:11

Peter Lawrey