C# StringBuilder和String淺析

來源:互聯網
上載者:User

C#語言還是比較常見的東西,這裡我們主要介紹C# StringBuilder和String,包括介紹大量字串拼接或頻繁對某一字串進行操作時最好使用 StringBuilder,不要使用 String等方面。

C# StringBuilder和String區別

String 在進行運算時(如賦值、拼接等)會產生一個新的執行個體,而 StringBuilder 則不會。所以在大量字串拼接或頻繁對某一字串進行操作時最好使用 StringBuilder,不要使用 String

另外,對於StringBuilder和String我們不得不多說幾句:

1.它是參考型別,在堆上分配記憶體

2.運算時會產生一個新的執行個體

3.String 對象一旦產生不可改變(Immutable)

4.定義相等運算子(== 和 !=)是為了比較 String 對象(而不是引用)的值

C# StringBuilder和String樣本:

 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4.    
  5. namespace Example22  
  6. {  
  7. class Program  
  8. {  
  9. static void Main(string[] args)  
  10. {  
  11. const int cycle = 10000;  
  12.    
  13. long vTickCount = Environment.TickCount;  
  14. String str = null;  
  15. for (int i = 0; i < cycle; i++)  
  16. str += i.ToString();  
  17. Console.WriteLine("String: {0} MSEL", Environment.TickCount - vTickCount);  
  18.    
  19. vTickCount = Environment.TickCount;  
  20. //看到這個變數名我就生氣,奇怪為什麼大家都使它呢? :)  
  21. StringBuilder sb = new StringBuilder();  
  22. for (int i = 0; i < cycle; i++)  
  23. sb.Append(i);  
  24. Console.WriteLine("StringBuilder: {0} MSEL", Environment.TickCount - vTickCount);  
  25.    
  26. string tmpStr1 = "A";  
  27. string tmpStr2 = tmpStr1;  
  28. Console.WriteLine(tmpStr1);  
  29. Console.WriteLine(tmpStr2);  
  30. //注意後面的輸出結果,tmpStr1的值改變並未影響到tmpStr2的值  
  31. tmpStr1 = "B";  
  32. Console.WriteLine(tmpStr1);  
  33. Console.WriteLine(tmpStr2);  
  34.    
  35. Console.ReadLine();  
  36. }  
  37. }  
  38. }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.