C# 中的 string、String、StringBuffer 內存處理性能 和 應用場景


一、System.String

string 等價於 System.String

stringSystem.String 的別名。

 聲明:

// 僅僅是一個聲明,內存中並沒有分配用來存儲值的空間。
string a1 = null;


// 等價於 "",以新建字符串長度為零的 String 對象,可以減少 NullReferenceException 發生的可能性。
string a1 = String.Empty;


// 在內存中分配了一個連續性的不可變的儲存空間。
System.String greeting = "Hello World!";


// 長字符串字面量拆分為較短的字符串,從而提高源代碼的可讀性。
// 以下代碼將較短的字符串連接起來,以創建長字符串字面量。 
// 在編譯時將這些部分連接成一個字符串。 無論涉及到多少個字符串,均不產生運行時性能開銷。
string text = "Historically, the world of data " +
"and the world of objects have not been well " +
"integrated. Programmers work in C# or Visual " +
"Basic and also in SQL or XQuery. On the one " +
"side are concepts such as classes, objects, " +
"fields, inheritance, and .NET Framework APIs. " +
"On the other side are tables, columns, rows, " +
"nodes, and separate languages for dealing with " +
"them. ";

System.String 是不可變類型。 也就是說,出現的用於修改對象的每個操作 System.String 實際上都會創建一個新的字符串。

如下舉例:

// 初始化 s1
// 內存為 s1 分配了存放字符的空間
string s1 = "A string is more ";

// 初始化 s2
// 內存為 s2 分配了存放字符的空間
string s2 = "than the sum of its chars.";

// 改變 s1 的值:
// 內存為 s1 另外重新分配了新值的空間
// 並指向新空間的地址,所以 s1 有了新的值
// 無用的s1舊值及空間等待GC垃圾回收
s1 += s2;

System.Console.WriteLine(s1);

以上,假設更多的+或+=等的多次賦值s1,那么 內存在不停的開辟新的空間存放新值賦予s1 ... ... 每次再需要GC分配、壓縮、清理... ...

對於此不可變類型,若執行大量字符串操作的例程 (例如在循環中多次修改字符串的應用程序) ,重復修改字符串可能會顯著降低性能。

作者:[Sol·wang] - 博客園,原文出處:https://www.cnblogs.com/Sol-wang/p/14792827.html

二、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[])字符搜索方式復雜。

場景

字符更改次數很少;

固定數量的拼接字符串聯操作;

大量的字符串搜索。

大量的未知的不確定的更改次數;

字符串非搜索場景。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM