Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why differ(!=,<>) is faster than equal(=,==)?

I've seen comments on SO saying "<> is faster than =" or "!= faster than ==" in an if() statement.

I'd like to know why is that so. Could you show an example in asm?

Thanks! :)

EDIT:

Source

Here is what he did.

  function Check(var MemoryData:Array of byte;MemorySignature:Array of byte;Position:integer):boolean;
   var i:byte;
   begin
    Result := True; //moved at top. Your function always returned 'True'. This is what you wanted?
    for i := 0 to Length(MemorySignature) - 1 do //are you sure??? Perhaps you want High(MemorySignature) here... 
    begin
{!}  if MemorySignature[i] <> $FF then //speedup - '<>' evaluates faster than '='
     begin
      Result:=memorydata[i + position] <> MemorySignature[i]; //speedup.
      if not Result then 
        Break; //added this! - speedup. We already know the result. So, no need to scan till end.
     end;
    end;
   end;
like image 998
Ivan Prodanov Avatar asked Jul 14 '09 10:07

Ivan Prodanov


People also ask

Why === is faster than ==?

So === faster than == in Javascript=== compares if the values and the types are the same. == compares if the values are the same, but it also does type conversions in the comparison. Those type conversions make == slower than ===.

How does == vs === differ?

The difference between == and === is that: == converts the variable values to the same type before performing comparison. This is called type coercion. === does not do any type conversion (coercion) and returns true only if both values and types are identical for the two variables being compared.

Which is faster == or !=?

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.

Why do we prefer === and !== Over == and != In JavaScript?

This is because the equality operator == does type coercion, meaning that the interpreter implicitly tries to convert the values before comparing. On the other hand, the identity operator === does not do type coercion, and thus does not convert the values when comparing.


2 Answers

I'd claim that this is flat out wrong except perhaps in very special circumstances. Compilers can refactor one into the other effortlessly (by just switching the if and else cases).

like image 97
Konrad Rudolph Avatar answered Oct 06 '22 21:10

Konrad Rudolph


It could have something to do with branch prediction on the CPU. Static branch prediction would predict that a branch simply wouldn't be taken and fetch the next instruction. However, hardly anybody uses that anymore. Other than that, I'd say it's bull because the comparisons should be identical.

like image 30
Jasper Bekkers Avatar answered Oct 06 '22 21:10

Jasper Bekkers