Aminos
Aminos

Reputation: 871

Which operator is faster: != or >

Which operator is faster: > or ==?

Example: I want to test a value (which can have a positive value or -1) against -1 :

if(time > -1)
// or
if (time != -1)

time has type "int"

Upvotes: 10

Views: 11283

Answers (3)

Lundin
Lundin

Reputation: 213286

It is platform-dependent. Generally though, those two operations will translate directly to the assembler instructions "branch if greater than" and "branch if not equal". It is unlikely that there is any performance difference between those two, and if there would be, it would be non-significant.

The only branch instruction which is ever so slightly faster than the others is usually "branch if zero"/"branch if not zero".

(In the dark ages when compilers sucked, C programmers therefore liked to write loops as down-counting to zero, instead of up-counting, so that comparisons would be done against zero instead of a value, in order to gain a few nanoseconds. Modern compilers can do that optimization themselves, but you still see such loops now and then.)

In general, you shouldn't concern yourself with micro-management of performance. If you spend time pondering if > is faster than !=, instead of pondering about program design, readability and functionality, you need to set your priorities straight asap.

Upvotes: 15

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

Semantically these conditions are different. The first one checks whether object time is positive or zero.

if(time > -1)

In this case it would be better to write

if( time >= 0 )

However some functions return either a non-negative value or -1. For example a search function can return -1 if it did not find an element in an array. Or -1 can signal an error state or an absence of a value.

In this case it is better to use condition

if ( time != -1 )

As for the speed when the compiler can generate only one mashine instruction to make the comparison in the both cases.

It is not the case when you should think about the speed. You should think about what condition is more expressive and shows the intention of the programmer.

Upvotes: 6

DevSolar
DevSolar

Reputation: 70213

The standard doesn't say. So it's up to what opcodes the given compiler generates in its given version, and how fast a given CPU executes them.

I.e., implementation / platform defined.

You can find out for a specific compiler / platform combination by looking at / benchmarking the executable code.

But I seriously doubt it will make much of a difference; this is the kind of micro-optimization that is almost always dwarfed by higher-level architectural decisions.

Upvotes: 21

Related Questions