使用 const 局部变量有运行时的好处吗?

Is there a runtime benefit to using const local variables?(使用 const 局部变量有运行时的好处吗?)
本文介绍了使用 const 局部变量有运行时的好处吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了确保它们不能被更改(根据编译器错误的调整)之外,JIT 是否对 const locals 进行任何优化?

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?

例如.

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

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

推荐答案

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

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 局部变量有运行时的好处吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to avoid #39;Unassigned Local Variable#39; defined inside a try-catch block(如何避免在try-Catch块中定义未赋值的局部变量)
When does a local variable inside a function *actually* gets allocated(函数内的局部变量何时*实际*被分配)
How to remove compiler error with struct: quot;Use of unassigned local variablequot;(如何使用 struct 删除编译器错误:“使用未分配的局部变量)
Strange behavior with actions, local variables and garbage collection in MVVM light Messenger(MVVM light Messenger 中的动作、局部变量和垃圾收集的奇怪行为)
Why does this (null || !TryParse) conditional result in quot;use of unassigned local variablequot;?(为什么这个 (null || !TryParse) 条件会导致“使用未分配的局部变量?)
Why does adding local variables make .NET code slower(为什么添加局部变量会使 .NET 代码变慢)