<= 和 >= 用于浮点类型时的性能

Performance of <= and >= when used on floating point types

我听说在使用 <=>= 运算符时,编译器会自动优化它:(int)Variable >= 2 变成 (int)Variable > 1。对于浮点类型,这在任何方面都是正确的吗?在我看来,(float)Variable >= 2 不能优化到 (float)Variable > 1.999999999 而不走向无穷大,要么导致它不可能,要么导致性能下降。 (我知道性能上的差异可能很小,但这正是我想知道的)

这不是真的,如果你检查生成的 IL 代码。例如,考虑以下 class:

public class C 
{
    public void M() 
    {
        float a = 4;
        float b = 5;
        bool result = a >= b;
    }
}

生成的IL代码如下:

.class public auto ansi beforefieldinit C
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig 
        instance void M () cil managed 
    {
        // Method begins at RVA 0x2050
        // Code size 22 (0x16)
        .maxstack 2
        .locals init (
            [0] float32,
            [1] float32,
            [2] bool
        )

        IL_0000: nop
        IL_0001: ldc.r4 4
        IL_0006: stloc.0
        IL_0007: ldc.r4 5
        IL_000c: stloc.1
        IL_000d: ldloc.0
        IL_000e: ldloc.1
        IL_000f: clt.un
        IL_0011: ldc.i4.0
        IL_0012: ceq
        IL_0014: stloc.2
        IL_0015: ret
    } // end of method C::M

    .method public hidebysig specialname rtspecialname 
        instance void .ctor () cil managed 
    {
        // Method begins at RVA 0x2072
        // Code size 8 (0x8)
        .maxstack 8

        IL_0000: ldarg.0
        IL_0001: call instance void [mscorlib]System.Object::.ctor()
        IL_0006: nop
        IL_0007: ret
    } // end of method C::.ctor

} // end of class C

如果您阅读上面生成的 IL 代码(用作对 IL 命令的参考 this),您会发现事实并非如此。

简而言之,在上面的 IL 代码中,float 数字被加载到堆栈中,然后使用 clt.un 操作,即:

Push 1 (of type int32) if value1 < value2, unsigned or unordered, else push 0.

然后使用ceq比较此操作的结果与0是否相等,其中:

Push 1 (of type int32) if value1 equals value2, else push 0.

并将上面的结果赋值给结果variable