string對象是不可變的
string @string =
@string = @string +
以上代碼讓人誤以為@string是能夠增加長度的
C#中不能使用new string()來構造一個string對象
string @string = new string(
@string = new string(
StringBuilder是可變的
用StringBuilder實現:
StringBuilder stringBuilder = new StringBuilder(
stringBuilder
StringBuilder在內部有一個足夠長的字符數組用於存放字符串對象
讓string和StringBuilder執行相同的操作:循環追加一個字符串
public static void CompareString()
UseString();
UseStringBuilder();
}
private static void UseString()
string @string =
DateTime startTime = DateTime
for (int i =
@string +=
}
DateTime endTime = DateTime
TimeSpan timeSpan = endTime
Console
}
private static void UseStringBuilder()
StringBuilder stringBuilder = new StringBuilder();
DateTime startTime = DateTime
for (int i =
stringBuilder
}
DateTime endTime = DateTime
TimeSpan timeSpan = endTime
Console
}
運行CompareString()函數得到以下結果
運行次數
時間
string
結論
補充
From:http://tw.wingwit.com/Article/program/net/201311/11387.html