StringBuilder類位於System.Text命名空間下,使用StringBuilder類每次重新生成新字符串時不是再生成一個新實例,而是直接再原來字符串占用的內存看空間上進行處理,而且它可以動態的分配占用內存空間大小。因此在字符串處理操作比較多的情況下,使用StringBuilder類可以大大提高系統的性能。
默認情況下,編譯器會自動為StringBuilder類型的字符串分配一定的內存容量,也可以在程序中直接修改其占用的字節數。
編寫測試代碼
using System; using System.Text; namespace StringBuilderExample { class Program { static void Main(string[] args) { StringBuilder str = new StringBuilder(); Console.WriteLine("字符串:{0},長度{1}", str, str.Length); Console.WriteLine("內存容量分配:{0}", str.Capacity); str = new StringBuilder("test string."); Console.WriteLine("字符串是:{0},長度:{1}", str, str.Length); Console.WriteLine("內存容量分配:{0}", str.Capacity); str.Append("append another string."); Console.WriteLine("字符串是:{0},長度:{1}", str, str.Length); Console.WriteLine("內存容量分配:{0}", str.Capacity); str = new StringBuilder("test string.", 5); Console.WriteLine("字符串是:{0},長度:{1}", str, str.Length); Console.WriteLine("內存容量分配:{0}", str.Capacity); str = new StringBuilder("test string.", 40); Console.WriteLine("字符串是:{0},長度:{1}", str, str.Length); Console.WriteLine("內存容量分配:{0}", str.Capacity); Console.ReadLine(); } } }
以下是.Net 4.5.2運行結果,版本不同可能會有差別