使用const局部变量是否有运行时优势?

Ric*_*lay 44 c# jit const

除了确保它们无法更改(编译器错误的调整)之外,JIT是否对const本地进行任何优化?

例如.

public static int Main(string[] args)
{
    const int timesToLoop = 50;

    for (int i=0; i<timesToLoop; i++)
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 81

生成的IL不同(使用Release模式):

using constant local                   using normal local
---------------------------------------------------------------------
.entrypoint                            .entrypoint
.maxstack 2                            .maxstack 2
.locals init (                         .locals init (
    [0] int32 i)                           [0] int32 timesToLoop,
L_0000: ldc.i4.0                           [1] int32 i)
L_0001: stloc.0                        L_0000: ldc.i4.s 50 
L_0002: br.s L_0008                    L_0002: stloc.0 
L_0004: ldloc.0                        L_0003: ldc.i4.0  
L_0005: ldc.i4.1                       L_0004: stloc.1 
L_0006: add                            L_0005: br.s L_000b 
L_0007: stloc.0                        L_0007: ldloc.1 
L_0008: ldloc.0                        L_0008: ldc.i4.1 
L_0009: ldc.i4.s 50                    L_0009: add
L_000b: blt.s L_0004                   L_000a: stloc.1 
L_000d: ret                            L_000b: ldloc.1 
                                       L_000c: ldloc.0 
                                       L_000d: blt.s L_0007
                                       L_000f: ret 
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,编译器将所有变量用法替换为常量的值,从而导致更小的堆栈.

  • @kenny我不同意它在功能上是相同的,因为可以改变非常数局部:P (2认同)

Mag*_*ndi 13

我使用Snippet Compiler为代码提供了快速的性能测试.我使用的代码如下:

    public static void Main()
    {
        DateTime datStart = DateTime.UtcNow;
        const int timesToLoop = 1000000;

        for (int i=0; i < timesToLoop; i++)
        {
            WL("Line Number " + i.ToString());
        }

        DateTime datEnd = DateTime.UtcNow;
        TimeSpan tsTimeTaken = datEnd - datStart;
        WL("Time Taken: " + tsTimeTaken.TotalSeconds);
        RL();
    }
Run Code Online (Sandbox Code Playgroud)

注意,WL和RL只是读取和写入控制台的辅助方法.

为了测试非常量版本,我只是删除了const关键字.结果令人惊讶:

                        Time Taken (average of 3 runs)

Using const keyword         26.340s
Without const keyword       28.276s
Run Code Online (Sandbox Code Playgroud)

我知道这是非常粗糙的'已经测试过,但const关键字的使用似乎算作有效的微优化.

  • 说到微优化,你应该使用`DateTime.UtcNow`而不是`DateTime.Now`,因为前者不需要从OS查找本地时区. (14认同)

小智 6

您的代码(使用const)实际上将编译为:

public static int Main(string[] args){    
    for (int i=0; i < 50; i++)  
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

而变量将编译为变量:

public static int Main(string[] args){
    int timesToLoop = 50;    
    for (int i=0; i < timesToLoop; i++)  
    {

    }
}
Run Code Online (Sandbox Code Playgroud)