除了确保它们不能被更改(根据编译器错误的调整)之外,JIT 是否对 const locals 进行了任何优化?
例如。
public static int Main(string[] args)
{
const int timesToLoop = 50;
for (int i=0; i<timesToLoop; i++)
{
// ...
}
}
生成的 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
正如您所看到的,编译器将所有变量使用替换为常量的值,从而导致堆栈更小。
我使用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();
}
请注意,WL 和 RL 只是读取和写入控制台的辅助方法。
为了测试非常量版本,我只是删除了const
关键字。结果令人惊讶:
Time Taken (average of 3 runs)
Using const keyword 26.340s
Without const keyword 28.276s
我知道这是非常粗略的'n'ready 测试,但使用const
关键字似乎算作有效的micro-optimization。
您的代码(使用 const)实际上将编译为:
public static int Main(string[] args){
for (int i=0; i < 50; i++)
{
}
}
而变量将编译为变量:
public static int Main(string[] args){
int timesToLoop = 50;
for (int i=0; i < timesToLoop; i++)
{
}
}
这不是一个答案,只是认为分享这个会很好,但是文章没有明确提到运行时的好处:
编码标准规则#2:尽可能使用 const
摘录:
推理: 尽可能多地使用 const 的好处是编译器强制防止意外写入应该是只读的数据。
一个区别是,如果您的程序集引用了const
另一个程序集中的字段,而您后来更改了该值,则引用程序集在重建之前仍将使用旧值。