Modifying immutable structures like string
s must be done by copying the structure, and by that, consuming more memory and slowing the application's run time (also increasing GC
time, etc...).
StringBuilder
comes to solve this problem by using the same mutable object for manipulations.
However:
when concatenating a string
in compile time as the following:
string myString = "123";
myString += "234";
myString += "345";
it will actually compile to something like that:
string myString = string.Concat("123", "234", "345");
this function is faster than working with StringBuilder
for the number of string
s entering the function is known.
so for compile-time-known string
concatenations you should prefer string.Concat()
.
as for unknown number of string
like in the following case:
string myString = "123";
if (Console.ReadLine() == "a")
{
myString += "234";
}
myString += "345";
Now the compiler can't use the string.Concat()
function, however, StringBuilder
appears to be more efficient in time and memory consumption only when the concatenation is done with 6-7 or more strings
.
Bad practice usage:
StringBuilder myString = new StringBuilder("123");
myString.Append("234");
myString.Append("345");
Fine practice usage (note that if
is used):
StringBuilder myString = new StringBuilder("123");
if (Console.ReadLine() == "a")
{
myString.Append("234");
}
myString.Append("345");
Best practice usage (note that while
loop is used):
StringBuilder myString = new StringBuilder("123");
while (Console.ReadLine() == "a")
{
myString.Append("234"); //Average loop times 4~ or more
}
myString.Append("345");
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…