leora
leora

Reputation: 196891

Should I use StringBuilder in C# if I have a large amount of concatenations even if the total length is small?

I am reviewing some code and I see a large amount of string concatentation but they are all very small strings. Something like this:

public string BuildList()
{
    return "A" + GetCount() + "B" + TotalCount() + "C" + AMountLeft()
         + "D" + DaysLeft + "R" +  Initials() + "E";
}

I am simplifying it but in total the longest string is about 300 characters and the number of + are about 20. I am trying to figure out if its worth to convert it to StringBuilder and do something like this:

public string BuildList()
{
    var sb = new StringBuilder();
    sb.Append("A");
    sb.Append(GetCount());
    sb.Append("B");
    sb.Append(TotalCount());
    sb.Append("C");
    sb.Append(AmountLeft());
    sb.Append("D");

    // etc . . 
}

I can't see a big difference from testing but wanted to see if there is a good breakeven rule about using StringBuilder (either length of string or number of different concatenations)?

Upvotes: 0

Views: 251

Answers (2)

Guffa
Guffa

Reputation: 700870

No, in that case there is no reason to favour a StringBuilder over string concatenation.

Your first code will become a single call to String.Concat, which would be marginally more efficient that using a StringBuilder.

Upvotes: 4

poke
poke

Reputation: 388403

For such a fixed situation with limited number of variable strings, and with a always-the-same part of text between those values, I would personally use string formatting there. That way, your intention gets a lot more clear and it’s easier to see what’s happening:

return string.Format("A{0}B{1}C{2}D{3}R{4}E",
    GetCount(), TotalCount(), AmountLeft(), DaysLeft(), Initials());

Note that string.Format is slightly slower than string.Concat (which as others said is used when you build a string using +). However, it’s unlikely that string concatenation will be a bottleneck in your application, so you should favor clarity over micro-optimization until that becomes an actual problem.

Upvotes: 5

Related Questions