Is there a runtime benefit to using const local variables?(使用 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 局部变量有运行时的好处吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 const 局部变量有运行时的好处吗?


- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01