您的位置:首页 > 编程语言

从减少装箱次数出发提升代码性能

2018-01-05 10:24 447 查看
测试tostring是否装箱的代码
结论tostring方法并不发生装箱,可利用此减少装箱次数,进而减少内存分配次数,降低GC工作量,最终提升代码性能

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace boxing
{
class Program
{
static void Main(string[] args)
{
//testboxing
Console.WriteLine(string.Format("{0}:{1}", 4, 5));

Console.WriteLine("----------");

//testnoboxing
var result = 1.ToString() + ":"+2.ToString();
Console.WriteLine(result);
}
}
}

其对应的IL指令
.method private hidebysig static void  Main(string[] args) cil managed
{
.entrypoint
// 代码大小       71 (0x47)
.maxstack  3
.locals init ([0] int32 V_0)
IL_0000:  ldstr      "{0}:{1}"
IL_0005:  ldc.i4.4
IL_0006:  box        [mscorlib]System.Int32
IL_000b:  ldc.i4.5
IL_000c:  box        [mscorlib]System.Int32
IL_0011:  call       string [mscorlib]System.String::Format(string,
object,
object)
IL_0016:  call       void [mscorlib]System.Console::WriteLine(string)

IL_001b:  ldstr      "----------"

IL_0020:  call       void [mscorlib]System.Console::WriteLine(string)
IL_0025:  ldc.i4.1  //将整数值 1 作为 int32 推送到计算堆栈上。
IL_0026:  stloc.0   //从计算堆栈的顶部弹出当前值并将其存储到索引 0 处的局部变量列表中。
IL_0027:  ldloca.s   V_0  //将位于特定索引处的局部变量的地址加载到计算堆栈上(短格式)。
IL_0029:  call       instance string [mscorlib]System.Int32::ToString()
IL_002e:  ldstr      ":"  //
IL_0033:  ldc.i4.2  //将整数值 2 作为 int32 推送到计算堆栈上。
IL_0034:  stloc.0   //从计算堆栈的顶部弹出当前值并将其存储到索引 0 处的局部变量列表中。
IL_0035:  ldloca.s   V_0  //将位于特定索引处的局部变量的地址加载到计算堆栈上(短格式)。
IL_0037:  call       instance string [mscorlib]System.Int32::ToString()
IL_003c:  call       string [mscorlib]System.String::Concat(string,
string,
string)
IL_0041:  call       void [mscorlib]System.Console::WriteLine(string)
IL_0046:  ret
} // end of method Program::Main
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: