【问题标题】:Performance of <= and >= when used on floating point types<= 和 >= 用于浮点类型时的性能
【发布时间】:2019-06-10 08:35:37
【问题描述】:

我听说当使用 &lt;=&gt;= 运算符时,编译器会自动对其进行优化:(int)Variable &gt;= 2 变为 (int)Variable &gt; 1。这对于浮点类型是否真的如此?在我看来 (float)Variable &gt;= 2 不能优化到 (float)Variable &gt; 1.999999999 而不走向无穷大,要么导致它不可能或对性能造成影响。 (我知道性能差异可能很小,但这只是我想知道的)

【问题讨论】:

  • 所有这些都有cpu指令JNE如果不相等则跳转,JE如果相等则跳转,JG如果大于则跳转,JLE如果小于或等于则跳转,JL如果小于则跳转,JGE 如果大于或等于则跳转。但是,如果这些变量被装箱,您最大的性能损失将是。事实上,如果您有性能问题,为什么不使用基准测试器并自己测试这些东西呢?

标签: c# performance operators


【解决方案1】:

如果您检查生成的 IL 代码,则不是这样。例如,考虑以下类:

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 操作,即:

如果 value1

然后使用ceq比较此操作的结果是否等于0,即:

如果 value1 等于 value2,则推 1(int32 类型),否则推 0。

上面的结果赋值给结果variable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多