先來看看一下這段代碼:
使用ToString()方法的代碼
1using System;
2
3namespace ConsoleApplication3
4{
5 class Program
6 {
7 static void Main(string[] args)
8 {
9 int i = 5;
10 string s = i.ToString();
11 }
12 }
13}
14
下面是它的IL代碼:使用ToString()的IL代碼
1.method private hidebysig static void Main(string[] args) cil managed
2{
3 .entrypoint
4 // Code size 12 (0xc)
5 .maxstack 1
6 .locals init ([0] int32 i,
7 [1] string s)
8 IL_0000: nop
9 IL_0001: ldc.i4.5
10 IL_0002: stloc.0
11 IL_0003: ldloca.s i
12 IL_0005: call instance string [mscorlib]System.Int32::ToString()
13 IL_000a: stloc.1
14 IL_000b: ret
15} // end of method Program::Main
好了,讓我再來看看另外的一段代碼,最後再做分析。
使用Convert.ToString()的代碼
1using System;
2
3namespace ConsoleApplication3
4{
5 class Program
6 {
7 static void Main(string[] args)
8 {
9 int i = 5;
10 string s = Convert.ToString(i);
11 }
12 }
13}
14
它的IL代碼:
使用Convert.ToString()的IL代碼
1.method private hidebysig static void Main(string[] args) cil managed
2{
3 .entrypoint
4 // Code size 11 (0xb)
5 .maxstack 1
6 .locals init ([0] int32 i,
7 [1] string s)
8 IL_0000: nop
9 IL_0001: ldc.i4.5
10 IL_0002: stloc.0
11 IL_0003: ldloc.0
12 IL_0004: call string [mscorlib]System.Convert::ToString(int32)
13 IL_0009: stloc.1
14 IL_000a: ret
15} // end of method Program::Main
好了,讓我們來看一下它們的區別吧:
| 區別 |
使用ToString()的代碼 |
使用Convert.ToString()的代碼 |
| Code size |
12 (0xc) |
11 (0xb) |
| IL代碼的第11行 |
ldloca.s i |
ldloc.0 |
| IL代碼的第12行 |
call instance string [mscorlib]System.Int32::ToString()
|
call string [mscorlib]System.Convert::ToString(int32)
|
總結一下:
首先,使用Convert.TOString()方法編譯出來的代碼較小;
其次,ldloca.s的作用是:將位於特定索引處的局部變數的地址載入到計算堆棧上(短格式)。而ldloc的作用是:將指定索引處的局部變數載入到計算堆棧上。也就是說它們的區別在於一個載入變數的地址,一個載入變數自身。
再有,就是最後調用轉換方法時,一個是執行個體方法,另一個是Convert的靜態ToString()方法。
那麼究竟使用那個好那?目前正在尋找資料研究中,希望大家也給我指點一下。