3

Say I have a StringBuilder object

var sb = new StringBuilder();

And an arbritrary array of strings

var s = new []{"a","b","c"};

Is this the 'quickest' way to insert them into the stringbuilder instance?

sb.Append(string.join(string.empty, s));

Or does StringBuilder have a function I have overlooked?

Edit: Sorry I dont know how many items sb will contain, or how many items may be in each String[].

1
  • there are so simple, i think this isn't important Commented Mar 26, 2012 at 9:47

5 Answers 5

8

If you mean by "quickest" most performant than better use:

for(int i = 0; i < myArrayLen; i++)
  sb.Append(myArray[i]);
Sign up to request clarification or add additional context in comments.

7 Comments

shouldn't that be for (int i = 0; ?
for is so faster than foreach or linq iterations
a for is always faster than any LINQ expression and a bit faster than a ForEach (as it goes by index instead of calling a method on IEnumerable interface)
@MassimilianoPeluso, Isn't correct. Is faster to use string.Concat if you have array of strings.
you are right I was referring to the performance difference between LINQ and a classic for(commented by @pylover)
|
1

string.Concat(...) should be faster than string.Join("", ...). Also, this depends on what else you're doing with your StringBuilder. If you're only performing a few concatenations then it can be faster not to use it.

More context always helps!

Comments

1

Believe it or not, but string.Concat is faster than StringBuilder when the strings are 4/5.
This article discuss the question very well.

1 Comment

It depends on what collection you pass to Concat method. If it is IEnumerable<string> then internally Concat uses StringBuilder class.
-1

To do this in one line without a loop, you could do this:

sb.Append(String.Join(Environment.NewLine, s));

and will also work where s is any type of

IEnumerable<string>

Comments

-2

I believe you already have the correct answer:

sb.Append(string.join(string.empty, s))

Comments

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.