Question

I understand the benefits of StringBuilder.

But if I want to concatenate 2 strings, then I assume that it is better (faster) to do it without StringBuilder. Is this correct?

At what point (number of strings) does it become better to use StringBuilder?

Was it helpful?

Solution

I warmly suggest you to read The Sad Tragedy of Micro-Optimization Theater, by Jeff Atwood.

It treats Simple Concatenation vs. StringBuilder vs. other methods.

Now, if you want to see some numbers and graphs, follow the link ;)

OTHER TIPS

But if I want to concatinate 2 strings, then I assume that it is better (faster) to do it without StringBuilder. Is this correct?

That is indeed correct, you can find why exactly explained very well on :

http://www.yoda.arachsys.com/csharp/stringbuilder.html

Summed up : if you can concatinate strings in one go like

var result = a + " " + b  + " " + c + ..

you are better off without StringBuilder for only on copy is made (the length of the resulting string is calculated beforehand.);

For structure like

var result = a;
result  += " ";
result  += b;
result  += " ";
result  += c;
..

new objects are created each time, so there you should consider StringBuilder.

At the end the article sums up these rules of thumb :

Rules Of Thumb

So, when should you use StringBuilder, and when should you use the string concatenation operators?

  • Definitely use StringBuilder when you're concatenating in a non-trivial loop - especially if you don't know for sure (at compile time) how many iterations you'll make through the loop. For example, reading a file a character at a time, building up a string as you go using the += operator is potentially performance suicide.

  • Definitely use the concatenation operator when you can (readably) specify everything which needs to be concatenated in one statement. (If you have an array of things to concatenate, consider calling String.Concat explicitly - or String.Join if you need a delimiter.)

  • Don't be afraid to break literals up into several concatenated bits - the result will be the same. You can aid readability by breaking a long literal into several lines, for instance, with no harm to performance.

  • If you need the intermediate results of the concatenation for something other than feeding the next iteration of concatenation, StringBuilder isn't going to help you. For instance, if you build up a full name from a first name and a last name, and then add a third piece of information (the nickname, maybe) to the end, you'll only benefit from using StringBuilder if you don't need the (first name + last name) string for other purpose (as we do in the example which creates a Person object).

  • If you just have a few concatenations to do, and you really want to do them in separate statements, it doesn't really matter which way you go. Which way is more efficient will depend on the number of concatenations the sizes of string involved, and what order they're concatenated in. If you really believe that piece of code to be a performance bottleneck, profile or benchmark it both ways.

System.String is an immutable object - it means that whenever you modify its content it will allocate a new string and this takes time (and memory?). Using StringBuilder you modify the actual content of the object without allocating a new one.

So use StringBuilder when you need to do many modifications on the string.

Not really...you should use StringBuilder if you concatenate large strings or you have many concatenations, like in a loop.

There's no definitive answer, only rules-of-thumb. My own personal rules go something like this:

  • If concatenating in a loop, always use a StringBuilder.
  • If the strings are large, always use a StringBuilder.
  • If the concatenation code is tidy and readable on the screen then it's probably ok.
    If it isn't, use a StringBuilder.

To paraphrase

Then shalt thou count to three, no more, no less. Three shall be the number thou shalt count, and the number of the counting shall be three. Four shalt thou not count, neither count thou two, excepting that thou then proceed to three. Once the number three, being the third number, be reached, then lobbest thou thy Holy Hand Grenade of Antioch

I generally use string builder for any block of code which would result in the concatenation of three or more strings.

  • If you concatenate strings in a loop, you should consider using StringBuilder instead of regular String
  • In case it's single concatenation, you may not see the difference in execution time at all

Here is a simple test app to prove the point:

class Program
{
    static void Main(string[] args)
    {
        const int testLength = 30000;
        var StartTime = DateTime.Now;

        //TEST 1 - String
        StartTime = DateTime.Now;
        String tString = "test string";
        for (int i = 0; i < testLength; i++)
        {
            tString += i.ToString();
        }
        Console.WriteLine((DateTime.Now - StartTime).TotalMilliseconds.ToString());
        //result: 2000 ms

        //TEST 2 - StringBuilder
        StartTime = DateTime.Now;
        StringBuilder tSB = new StringBuilder("test string");
        for (int i = 0; i < testLength; i++)
        {
            tSB.Append(i.ToString());
        }
        Console.WriteLine((DateTime.Now - StartTime).TotalMilliseconds.ToString());
        //result: 4 ms

        Console.ReadLine();
    }
}

Results:

  • 30'000 iterations

    • String - 2000 ms
    • StringBuilder - 4 ms
  • 1000 iterations

    • String - 2 ms
    • StringBuilder - 1 ms
  • 500 iterations

    • String - 0 ms
    • StringBuilder - 0 ms

But if I want to concatenate 2 strings, then I assume that it's better and faster to do so without StringBuilder. Is this correct?

Yes. But more importantly, it is vastly more readable to use a vanilla String in such situations. Using it in a loop, on the other hand, makes sense and can also be as readable as concatenation.

I’d be wary of rules of thumb that cite specific numbers of concatenation as a threshold. Using it in loops (and loops only) is probably just as useful, easier to remember and makes more sense.

As long as you can physically type the number of concatenations (a + b + c ...) it shouldn't make a big difference. N squared (at N = 10) is a 100X slowdown, which shouldn't be too bad.

The big problem is when you are concatenating hundreds of strings. At N=100, you get a 10000X times slowdown. Which is pretty bad.

I don't think there's a fine line between when to use or when not to. Unless of course someone performed some extensive testings to come out with the golden conditions.

For me, I will not use StringBuilder if just concatenating 2 huge strings. If there's loop with an undeterministic count, I'm likely to, even if the loop might be small counts.

A single concatenation is not worth using a StringBuilder. I've typically used 5 concatenations as a rule of thumb.

The StringBuilder class provides the developer with a set of methods that allows manipulation of a mutable string of characters, it can be used when you want to modify a string without creating a new object, thus eliminating the overhead or bottleneck issue of the normal String concatenation.

Using the StringBuilder class can boost performance when concatenating many strings together in a loop.

The following is a list of a few operations that can be performed to manipulate a string using the StringBuilder Class in .NET

Append: Appends information to the end of the current StringBuilder.

AppendFormat: Replaces a format specifier passed in a string with formatted text.

Insert: Inserts a string or object into the specified index of the current StringBuilder.

Remove: Removes a specified number of characters from the current StringBuilder.

Replace: Replaces a specified character at a specified index.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top