How C# or any other language NOT Equal to operator performs

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 equal
  • jne - Jump it not equal
  • These, or any of the jxx instructions 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 a System.Diagnostics.Stopwatch , by wrapping them in calls to Start() and Stop() . 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.


    I think on the binary level, it's a single operation (don't quote me), so either is pretty much the same.

    That said, if you're trying to optimize at this level, you're doing something wrong. This isn't assembly.


    In my opinion, generally, the NOT EQUAL operation (!=) should be faster than EQUAL (==), as the NOT EQUAL operation will return result as soon as there's some chunk value (it based on your OS is 32-bit or 64-bit or so on) is not equal.

    In your case, 2 operations should be faster equal, as 100 is an 4-byte integer.

    And I think the 2 operator does not have the same implementation.

    链接地址: http://www.djcxy.com/p/31570.html

    上一篇: C ++编译器是否可以识别2的幂次?

    下一篇: C#或任何其他语言如何不等于操作员执行