1

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[] ?

Béranger
  • 671
  • 8
  • 23
  • 1
    This is the kind of question that is best answered with real-world examples and benchmarks rather than pure theoretical examination. Can you provide examples that you would like to see benchmarked? – Louis Sep 26 '16 at 15:54
  • 2
    See http://jonskeet.uk/csharp/stringbuilder.html – Jon Skeet Sep 26 '16 at 15:55
  • See [this answer](http://stackoverflow.com/a/1532499/579895) – Pikoh Sep 26 '16 at 15:56
  • 1
    Note that `a += b` or `a = a + b` gets translated to `a = string.Concat(a, b)` by the C# compiler – Matias Cicero Sep 26 '16 at 15:56
  • What is more, you would never use `string[]` in C# for this, as arrays in C# have constant length and changing it requires allocation of new memory and copying the contents. You might try to use `List`, but `StringBuilder` or `String.Concat` is the way to go, depending on the case. – kiziu Sep 26 '16 at 15:58
  • Another tangentially relevant SO post: http://stackoverflow.com/questions/10341188/string-concatenation-using-operator – code11 Sep 26 '16 at 15:58
  • 3
    They serve two different purposes. `StringBuilder` is used to directly concatenate an arbitrary number of strings, whether in a collection or not - `string.Join` is used to concatenate strings (from a collection) with a separator. If you want to use `Join` to concatenate strings with an empty separator there's nothing stopping you, but it's not the _intended_ purpose. – D Stanley Sep 26 '16 at 15:59
  • the question is do you want to compare string.join or string[].join? – Dominik Sep 26 '16 at 16:05
  • @DStanley If you don't have a separator, then you should be using `Concat`. It's a method specifically to concatenate an arbitrary number of strings. – Servy Sep 26 '16 at 16:05

1 Answers1

2

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.

Dominik
  • 1,623
  • 11
  • 27