.Net 中的 string、String、StringBuffer 記憶體處理性能 和 應用場景
一、System.String
string
等價於 System.String
。
string
是 System.String
的別名。
聲明:
1 string a1 = null; // 僅僅是一個聲明,記憶體中並沒有分配用來存儲值的空間。 2 3 string a1 = String.Empty; // 等價於 "",以新建字元串長度為零的 String 對象,可以減少 NullReferenceException 發生的可能性。 4 5 System.String greeting = "Hello World!"; // 在記憶體中分配了一個連續性的不可變的儲存空間。 6 7 // 長字元串字面量拆分為較短的字元串,從而提高源程式碼的可讀性。 8 // 以下程式碼將較短的字元串連接起來,以創建長字元串字面量。 在編譯時將這些部分連接成一個字元串。 無論涉及到多少個字元串,均不產生運行時性能開銷。 9 string text = "Historically, the world of data and the world of objects " + 10 "have not been well integrated. Programmers work in C# or Visual Basic " + 11 "and also in SQL or XQuery. On the one side are concepts such as classes, " + 12 "objects, fields, inheritance, and .NET Framework APIs. On the other side " + 13 "are tables, columns, rows, nodes, and separate languages for dealing with " + 14 "them. Data types often require translation between the two worlds; there are " + 15 "different standard functions. Because the object world has no notion of query, a " + 16 "query can only be represented as a string without compile-time type checking or " + 17 "IntelliSense support in the IDE. Transferring data from SQL tables or XML trees to " + 18 "objects in memory is often tedious and error-prone.";
System.String
是不可變類型。 也就是說,出現的用於修改對象的每個操作 System.String
實際上都會創建一個新的字元串。
如下舉例:
1 // 初始化 s1 2 // 記憶體為 s1 分配了存放字元的空間 3 string s1 = "A string is more "; 4 5 // 初始化 s2 6 // 記憶體為 s2 分配了存放字元的空間 7 string s2 = "than the sum of its chars."; 8 9 // 記憶體為 s1 重新分配了新值的空間 10 // 並指向新空間的地址,所以 s1 有了新的值 11 // 無用的s1舊值等待GC垃圾回收 12 s1 += s2; 13 14 System.Console.WriteLine(s1);
以上,假設更多的+或+=等的多次賦值s1,那麼 記憶體在不停的開闢新的空間存放新值賦予s1 … … 每次再需要GC分配、壓縮、清理… …
對於執行大量字元串操作的常式 (例如在循環中多次修改字元串的應用程式) ,重複修改字元串可能會顯著降低性能。
二、System.Text.StringBuilder
System.Text.StringBuilder
對象在緩衝區操作,是一個可變字元串類,緩衝區可隨時增加或減少或刪除或替換等的字元串的長度。
StringBuilder strb = new StringBuilder(); strb.Append('*', 10).Append(" Adding Text to a StringBuilder Object ").Append('*', 10); strb.AppendLine("\n"); strb.AppendLine("Some code points and their corresponding characters:"); for (int ctr = 50; ctr <= 60; ctr++) { strb.AppendFormat("{0,12:X4} {1,12}", ctr,Convert.ToChar(ctr)); strb.AppendLine(); }
三、適用場景
string、String |
StringBuilder |
連續性的不可變的記憶體空間長度; 開闢新的記憶體空間存放變更後的值; 藉助IndexOf、Substring等進行字元搜索。 |
緩衝區可伸縮的記憶體空間長度; (Chars[])字元搜索方式複雜。 |
字元更改次數很少; 固定數量的串聯拼接操作; 大量的字元串搜索。 |
大量的未知的不確定的更改次數; 字元串非搜索場景 |