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

9
  • 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? Commented Sep 26, 2016 at 15:54
  • 2
    See jonskeet.uk/csharp/stringbuilder.html Commented Sep 26, 2016 at 15:55
  • See this answer Commented Sep 26, 2016 at 15:56
  • 1
    Note that a += b or a = a + b gets translated to a = string.Concat(a, b) by the C# compiler Commented Sep 26, 2016 at 15:56
  • 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. Commented Sep 26, 2016 at 15:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

The second question is using StringBuilder versus calling Join on a string array.
Thanks for that explaination. Editing my answer
"StringBuilder is more performant (that are some nanosecs per call) than using .Join on an string[]" how do you know this?
@stuartd The question is joining multiple string[]. Not using string.Join. At least i think so
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.