4、提取看似无用的委托变量,减少构造开销
using System; namespace ShouldCode { public class ShouldDelegateVariable { public void Should() { Action show = Show; for (int i = 0 ; i < 10 ; i++) { DoShow(show); } /*IL_0008: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_000d: stloc.0 IL_000e: ldc.i4.0 IL_000f: stloc.1 IL_0010: br.s IL_0020 // loop start (head: IL_0020) IL_0012: nop IL_0013: ldarg.0 IL_0014: ldloc.0 IL_0015: call instance void ShouldCode.ShouldDelegateVariable::DoShow(class [mscorlib]System.Action) IL_001a: nop IL_001b: nop IL_001c: ldloc.1 IL_001d: ldc.i4.1 IL_001e: add IL_001f: stloc.1 IL_0020: ldloc.1 IL_0021: ldc.i4.s 10 IL_0023: clt IL_0025: stloc.2 IL_0026: ldloc.2 IL_0027: brtrue.s IL_0012 // end loop */ } public void Not() { for (int i = 0 ; i < 10 ; i++) { DoShow(Show); } /* // loop start (head: IL_001e) IL_0005: nop IL_0006: ldarg.0 IL_0007: ldarg.0 IL_0008: ldftn instance void ShouldCode.ShouldDelegateVariable::Show() IL_000e: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_0013: call instance void ShouldCode.ShouldDelegateVariable::DoShow(class [mscorlib]System.Action) IL_0018: nop IL_0019: nop IL_001a: ldloc.0 IL_001b: ldc.i4.1 IL_001c: add IL_001d: stloc.0 IL_001e: ldloc.0 IL_001f: ldc.i4.s 10 IL_0021: clt IL_0023: stloc.1 IL_0024: ldloc.1 IL_0025: brtrue.s IL_0005 // end loop */ } public void DoShow(Action action) { action?.Invoke(); } public void Show() { Console.WriteLine("看起来代码是一样的,其实涉及到内存分配问题!"); Console.WriteLine("提取变量可以减少委托构造开销,注意多出的开销在 not 演示的 loop 范围里的 newobj !"); } } }
补充: newobj 指令为类型分配内存资源。一般都是 new。