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 局部变量有运行时的好处吗?


基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01