Hi which one is faster
int a = 100;
//First Way
if (a != 100)
{
//Do something when a is not equal to 100
}
else
{
//Do something when a is equal to 100
}
//Second Way
if (a == 100)
{
//Do something when a is equal to 100
}
else
{
//Do something when a is not equal to 100
}
I thinks second way is faster , but I am curious to Know how NOT EQUAL (!=) operator is solved . Is it like first it implements equal(==) operation and then the result is negated like !(a==100) ? Any help will be highly appericiated.
There is no difference between the two whatsoever. For an
int, it all boils down to one of two assembly instructions on x86:je– Jump if equaljne– Jump it not equalThese, or any of the
jxxinstructions all take the same amount of time.See also my other answer related to your question.
Since you really seem to care, I suggest you test it yourself. Write up two loops, one that uses
==and one that uses!=. Then time them with aSystem.Diagnostics.Stopwatch, by wrapping them in calls toStart()andStop(). Then compare. With a high enough number of iterations through the loop (to minimize other timing errors like context switches, interrupts, etc.) you will see no difference.