Béranger Béranger - 2 months ago 19
C# Question

String concatenation : += operator versus string array joined

The concatenation in many language using the

+=
operator create a new string instance. It is preffered to use a
string[]
that we join at the end.

In Javascript :

var myString = new Array("Hello");
myString.push(" ");
myString.push("world !");
console.log(myString.join(''));


is more efficient that :

var myString = "Hello";
myString += " ";
myString += "world !";
console.log(myString);


In C#, does the
+=
operator create a new string ?
Is the StringBuilder more efficient that using a
string[]
?

Answer

In C#, does the += operator create a new string ?

String is immutable in C# and Java. That means you can not modify it. Every method that modifys a string (+= executes a method too) returns a new instance of a string.

Is the StringBuilder more efficient that using .Join() on a string[] ?

StringBuilder is more performant (that are some nanosecs per call) than using .Join on an string[]. So it does make "sence" when you do that really often in a loop or something.