Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the inequality operator faster than the equality operator?

I know this is a micro-optimization, so I ask out of pure curiosity.

Logically, a microprocessor does not need to compare all the bits of both operands of an equality operator in order to determine a "FALSE" result.

Note, this is programming-related because it affects the execution speed of a program.

like image 733
Mackenzie Avatar asked Jun 22 '09 23:06

Mackenzie


People also ask

Which is faster equals or ==?

Specifically with regard to strings, yes, == is slightly faster than equals , because the first thing the String.

Which comparison operator is faster?

Some processors are quicker when comparing against zero. So > 0 might be faster than >= 1 , as an example. @Simple A decent compiler will replace >= 1 with > 0 if it's faster.

What is an inequality operator?

The inequality operator ( != ) checks whether its two operands are not equal, returning a Boolean result. Unlike the strict inequality operator, it attempts to convert and compare operands that are of different types.


2 Answers

Usually, the microprocessor does comparison using electrical gates and not step by step like that. It checks all bits at once.

like image 90
mmx Avatar answered Sep 20 '22 18:09

mmx


This depends on your platform, but in general, it will perform identically.

For example, on X86, you can see this by looking at how assembly works. Check out the X86 assembly control flow operations - whether you're doing equality or inequality, it's done as 2 operations.

First, you do a CMP (comparison) operation. You then do a check to see if the comparison is equal, not equal, etc. This is just checking the results of the compare - in both cases, you're doing 2 operations.

In many higher level programming languages, however, things are different. Many languages define inequality in terms of equality - to check inequality, you do the equality check, then a second check to see if it's false. This causes equality to be (microscopically) faster in these languages. Many languages allow you to specifically write both, as well - but many people tend to write inequality in terms of equality, which again makes equality, in general, slightly faster.

like image 30
Reed Copsey Avatar answered Sep 22 '22 18:09

Reed Copsey