2

Is it better to use string.concat or string builder? Can anyone explain me at what circumstance I should use the two?

There is a question here ,that explains the performance , I want to understand where to use string.concat and where to avoid it ?

Thanks in advance.

Community
  • 1
  • 1
Nisha
  • 1,783
  • 4
  • 18
  • 34
  • 4
    `String.Concat` uses `StringBuilder`, so they are roughly equal – Dmitry Bychenko Sep 12 '16 at 09:16
  • 4
    Use `StringBuilder` if you are concatenating in a loop or making a lot of separate calls to Concat(), otherwise you can use `String.Concat()` – Matthew Watson Sep 12 '16 at 09:19
  • If you have already all the values you want to concenate(in a `List` or `String[]` or another kind of `IEnumerable`) use `String.Concat`. If you need to determine the strings that you want to append(f.e. in a loop with additional logic) use your own `StringBuilder`. Otherwise you are creating many unnecessary `StringBuilder`-instances in `Concat`. – Tim Schmelter Sep 12 '16 at 09:24
  • Didnt the link you provide already have an answer to this ? http://stackoverflow.com/a/1612835/3956100 – Niklas Sep 12 '16 at 10:35

3 Answers3

5

As you can see from the reference source

http://referencesource.microsoft.com/#mscorlib/system/string.cs,206408f6325aea24

    [ComVisible(false)]
    public static String Concat(IEnumerable<String> values) {
        if (values == null)
            throw new ArgumentNullException("values");
        Contract.Ensures(Contract.Result<String>() != null);
        Contract.EndContractBlock();

        StringBuilder result = StringBuilderCache.Acquire();
        using(IEnumerator<String> en = values.GetEnumerator()) {
            while (en.MoveNext()) {
                if (en.Current != null) {
                    result.Append(en.Current);
                }
            }            
        }
        return StringBuilderCache.GetStringAndRelease(result);            
    }

String.Concat uses StringBuilder that's why both methods are roughly the same.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 4
    This doesn't address the common pattern when many separate calls are being made to `string.Concat()`, e.g. when it is called in a loop. In such cases, `StringBuilder` should be used. – Matthew Watson Sep 12 '16 at 09:20
3

string.Concat uses StringBuilder to do its job. So if you have a single operation that concats multiple strings I prefer string.Concat because of the shorter syntax.

 var result = string.Concat("abc", "def");

If you have to perform multiple operations, then one single StringBuilder instance should be used, to be more performant (because multiple string.Concat calls will instantiate their own StringBuilder each time).

 var builder = new StringBuilder();
 for (int i = 0; i < numberOfOperations; i++)
 {
      builder.Append(getStringResult());
 }
Ralf Bönning
  • 14,515
  • 5
  • 49
  • 67
  • I was using string.concat to generate a error message in my message box control, in few places in my project. The error message uses different values so I couldn't use a common method or string builder. I am right in using string.concat here? – Nisha Sep 12 '16 at 09:36
  • @Nisha: If you need multiple string.Concat operations to create the resulting string, then StringBuilder is to prefer. If all can be done in one operation that concats multiple strings together, then string.Concat is nicer to read. – Ralf Bönning Sep 12 '16 at 09:36
  • oh Ok. I get it now. Thank you. – Nisha Sep 12 '16 at 09:37
1

Also, if you have a string collection of known size, you can use StringBuilder and initialize it's capacity by a sum of lengths - it will save some time required to increase the size of internal buffer of StringBuilder. String.Concat does not do that, as you can see in Dmitry's comment.

kiziu
  • 1,111
  • 1
  • 11
  • 15