Is < faster than <=?

后端 未结 14 860
孤城傲影
孤城傲影 2020-11-22 13:43

Is if( a < 901 ) faster than if( a <= 900 ).

Not exactly as in this simple example, but there are slight performance changes on loop

14条回答
  •  失恋的感觉
    2020-11-22 14:10

    Only if the people who created the computers are bad with boolean logic. Which they shouldn't be.

    Every comparison (>= <= > <) can be done in the same speed.

    What every comparison is, is just a subtraction (the difference) and seeing if it's positive/negative.
    (If the msb is set, the number is negative)

    How to check a >= b? Sub a-b >= 0 Check if a-b is positive.
    How to check a <= b? Sub 0 <= b-a Check if b-a is positive.
    How to check a < b? Sub a-b < 0 Check if a-b is negative.
    How to check a > b? Sub 0 > b-a Check if b-a is negative.

    Simply put, the computer can just do this underneath the hood for the given op:

    a >= b == msb(a-b)==0
    a <= b == msb(b-a)==0
    a > b == msb(b-a)==1
    a < b == msb(a-b)==1

    and of course the computer wouldn't actually need to do the ==0 or ==1 either.
    for the ==0 it could just invert the msb from the circuit.

    Anyway, they most certainly wouldn't have made a >= b be calculated as a>b || a==b lol

提交回复
热议问题