有一个运行时的好处是用const的局部变量? [英] Is there a runtime benefit to using const local variables?

查看:142
本文介绍了有一个运行时的好处是用const的局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的确保它们不能被改变(到一个编译器错误的曲调)之外,没有了JIT作出任何的优化为常量当地人



例如

 公共静态INT主要(字串[] args)
{
const int的timesToLoop = 50;

的for(int i = 0; I< timesToLoop;我++)
{
// ...
}
}


解决方案

生成的IL是不同的(使用拍摄模式):

 使用当地不变采用本地正常
--------------------- ------------------------------------------------
.entrypoint .entrypoint
.maxstack 2 .maxstack 2
.locals的init(.locals的init(
[0] INT32我)[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.0 L_0003:ldc.i4.0
L_0005:ldc.i4.1 L_0004:stloc.1
L_0006:添加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:加
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

正如你所看到的编译器,这导致在一个较小的堆栈中的常量的值替换所有变量的用法。


Outside of the ensuring that they cannot be changed (to the tune of a compiler error), does the JIT make any optimisations for const locals?

Eg.

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

    for (int i=0; i<timesToLoop; i++)
    {
        // ...
    }
}

解决方案

The generated IL is different (using Release mode):

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

As you can see the compiler replaces all variable usages by the value of the constant which results in a smaller stack.

这篇关于有一个运行时的好处是用const的局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆