例说装箱与拆箱性能消耗
我们一直都知道,C#中的装箱与拆箱操作存在性能消耗。
并且,泛型的使用能较好的解决这个问题,具体内容请阅读《C#泛型好处知多少using System;using System.Diagnostics;namespace BoxExp{ class Program { static void Main(string[] args) { String str1 = string.Empty; String str2 = string.Empty;//代码片段1 Stopwatch sw1 = new Stopwatch(); sw1.Start(); for (int i=0; i < 1000000; i++) { str1 = "Hello," + i;//装箱操作 } sw1.Stop(); Console.WriteLine("str1:{0} time:{1}", str1, 1000* sw1.Elapsed.TotalSeconds);//代码片段2 Stopwatch sw2 = new Stopwatch(); sw2.Start(); for (int i = 0; i < 1000000; i++) { str2 = "Hello," + i.ToString();//无装箱操作 } sw2.Stop(); Console.WriteLine("str2:{0} time:{1}", str2, 1000 * sw2.Elapsed.TotalSeconds); object obj = 1; int sum1 = 0; int sum2 = 0;//代码片段3 Stopwatch sw3 = new Stopwatch(); sw3.Start(); for (int i = 0; i < 1000000; i++) { sum1 = i + (Int32)obj;//拆箱操作 } sw3.Stop(); Console.WriteLine("sum1:{0} time:{1}", sum1, 1000 * sw3.Elapsed.TotalSeconds);//代码片段4 Stopwatch sw4 = new Stopwatch(); sw4.Start(); for (int i = 0; i < 1000000; i++) { sum2 = i + 1;//无拆箱 } sw4.Stop(); Console.WriteLine("sum2:{0} time:{1}", sum2, 1000 * sw4.Elapsed.TotalSeconds); } }}
代码中已用注释标示出哪里需要装箱与拆箱操作。
对于装箱与拆箱不做任何解释,直接上结果。
确实,存在装箱操作或者拆箱操作的代码耗时比无装拆箱操作的代码耗时要多。上面给出的仅其中一次典型结果。但是每次基本都跟此次结果无太大差距。
顺便给出IL代码。
代码片段1对应的部分IL代码
...(省略其他) IL_001b: stloc.3 IL_001c: br.s IL_0035 IL_001e: nop IL_001f: ldstr "Hello," IL_0024: ldloc.3 IL_0025: box [mscorlib]System.Int32 IL_002a: call string [mscorlib]System.String::Concat(object,object)...
注意:box 装箱操作
代码片段2对应的部分IL代码
... IL_0084: stloc.3 IL_0085: br.s IL_009f IL_0087: nop IL_0088: ldstr "Hello," IL_008d: ldloca.s i IL_008f: call instance string [mscorlib]System.Int32::ToString() IL_0094: call string [mscorlib]System.String::Concat(string, string) ...
注意:无box 无装箱操作
代码片段3对应的部分IL代码
... IL_00fe: stloc.3 IL_00ff: br.s IL_0112 IL_0101: nop IL_0102: ldloc.3 IL_0103: ldloc.s obj IL_0105: unbox.any [mscorlib]System.Int32 IL_010a: add...
注意:unbox 拆箱操作
代码片段4对应的部分IL代码
... IL_016d: ldloc.3 IL_016e: ldc.i4.1 IL_016f: add IL_0170: stloc.s sum2 IL_0172: nop IL_0173: ldloc.3 IL_0174: ldc.i4.1 IL_0175: add...
注意:无unbox 无拆箱操作
就到这了。