有人可以告诉我在内存中创建的字符串实例的总数,例如下面的内容吗? 简要说明将受到很多赞赏。
我的代码:
String A = "1" + "2" + "3" ; /* total number of strings in memory = ?? */
String B = "1" + "2" + "1" ; /* total number of strings in memory = ?? */
string one = "1";
string two = "2";
string three = "3";
String C = one + two + three; /* total number of strings in memory = ?? */
String D = one + two + one; /* total number of strings in memory = ?? */
答案 0 :(得分:4)
来自C# documentation on string concatenation:
使用+运算符连接字符串文字或字符串常量时,编译器会创建一个字符串。没有运行时连接。
这意味着你的连接每个只创建一个字符串,所以总的来说你的例子在内存中产生7个字符串:
String A = "1" + "2" + "3" ; // 1 (concatenation of literals)
String B = "1" + "2" + "1" ; // 1 (concatenation of literals)
string one = "1"; // 1
string two = "2"; // 1
string three = "3"; // 1
String C = one + two + three; // 1 (concatenation of string constants)
String D = one + two + one; // 1 (concatenation of string constants)
// = 7 strings in total
但是,如果在循环中进行串联,则会生成更多字符串,例如:
for word in text:
result_string += word // Bad! Creates a new string in each iteration
在这种情况下,最好使用StringBuilder.append
:
System.Text.StringBuilder builder = new System.Text.StringBuilder();
for word in text:
builder.Append(word) // Good! Just appends to the string builder