ToString()方法與Convert.ToString()的差異

來源:互聯網
上載者:User

先來看看一下這段代碼:

使用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()方法。

那麼究竟使用那個好那?目前正在尋找資料研究中,希望大家也給我指點一下。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.