如何在C#编译器优化的代码片段? [英] How does the C# compiler optimize a code fragment?
本文介绍了如何在C#编译器优化的代码片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这样的代码
for(int i=0;i<10;i++)
{
int iTemp;
iTemp = i;
//.........
}
编译器实例化iTemp 10次?
Does the compiler instantinate iTemp 10 times?
还是优化它?
我的意思是如果我将循环重写为
I mean if i rewrite the loop as
int iTemp;
for(int i=0;i<10;i++)
{
iTemp = i;
//.........
}
它会更快?
推荐答案
Using reflector you can view the IL generated by the C# compiler.
.method private hidebysig static void Way1() cil managed
{
.maxstack 2
.locals init (
[0] int32 i)
L_0000: ldc.i4.0
L_0001: stloc.0
L_0002: br.s L_0008
L_0004: ldloc.0
L_0005: ldc.i4.1
L_0006: add
L_0007: stloc.0
L_0008: ldloc.0
L_0009: ldc.i4.s 10
L_000b: blt.s L_0004
L_000d: ret
}
.method private hidebysig static void Way2() cil managed
{
.maxstack 2
.locals init (
[0] int32 i)
L_0000: ldc.i4.0
L_0001: stloc.0
L_0002: br.s L_0008
L_0004: ldloc.0
L_0005: ldc.i4.1
L_0006: add
L_0007: stloc.0
L_0008: ldloc.0
L_0009: ldc.i4.s 10
L_000b: blt.s L_0004
L_000d: ret
}
它们是完全一样的,所以在声明iTemp时没有性能差异。
They're exactly the same so it makes no performance difference where you declare iTemp.
这篇关于如何在C#编译器优化的代码片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文