Nov 162011
 

Given most programming problems there is an almost endless number of ways to implement a solution for even the most simple task. One of those tasks that many take for granted is string manipulation. When talking to a friend recently about this it brought up the question of which method is faster and better performing. So I decided I needed to look at execution speeds and memory usage of three of the main string manipulation implementations; String.Format, StringBuilder and String Concatenation.

To do this this testing I developed several test cases within the same project and monitored execution speed and memory usage at the end of each case. All tests were done in C# .NET 4.0. My end result is a sample e-mail body that contains several dynamic elements.

I created the following three code snippets in order to test my theories.

Test Case 1: String Concatenation

string s = "Date: " + DateTime.Now.ToString();
s += Environment.NewLine + Environment.NewLine;
s += "Hello " + sRecipientName;
s += Environment.NewLine + Environment.NewLine;
s += "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce consequat fringilla nulla at ultrices. Ut odio dui, commodo id porta a, ultricies quis nulla. Aliquam sollicitudin lectus quis nisl varius fringilla. Morbi tempor nunc pulvinar tellus ultrices sodales. Integer libero nunc, fermentum in tempus et, laoreet ut mi. ";
s += Environment.NewLine + Environment.NewLine;
s += "Nullam mollis nunc eu lorem mattis ac facilisis ligula suscipit. Integer imperdiet dolor adipiscing eros semper at rutrum lectus facilisis. Nam a urna justo. Aenean magna leo, rutrum dapibus facilisis quis, interdum nec lacus. ";
s += Environment.NewLine + Environment.NewLine;
s += "Sincerly, ";
s += Environment.NewLine + Environment.NewLine;
s += sSenderName;

Console.WriteLine(s);

Test Case 2: String Builder

StringBuilder sb = new StringBuilder();

sb.Append("Date: ");
sb.Append(DateTime.Now);
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.Append("Hello ");
sb.Append(sRecipientName);
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.AppendLine("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce consequat fringilla nulla at ultrices. Ut odio dui, commodo id porta a, ultricies quis nulla. Aliquam sollicitudin lectus quis nisl varius fringilla. Morbi tempor nunc pulvinar tellus ultrices sodales. Integer libero nunc, fermentum in tempus et, laoreet ut mi. ");
sb.Append(Environment.NewLine);
sb.AppendLine("Nullam mollis nunc eu lorem mattis ac facilisis ligula suscipit. Integer imperdiet dolor adipiscing eros semper at rutrum lectus facilisis. Nam a urna justo. Aenean magna leo, rutrum dapibus facilisis quis, interdum nec lacus. ");
sb.Append(Environment.NewLine);
sb.AppendLine("Sincerly, ");
sb.Append(Environment.NewLine);
sb.Append(sSenderName);

Console.WriteLine(sb);

Test Case 3: String.Format

Console.WriteLine(String.Format("Date: {0}{1}{2}Hello {3},{4}{5}Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce consequat fringilla nulla at ultrices. Ut odio dui, commodo id porta a, ultricies quis nulla. Aliquam sollicitudin lectus quis nisl varius fringilla. Morbi tempor nunc pulvinar tellus ultrices sodales. Integer libero nunc, fermentum in tempus et, laoreet ut mi. {6}{7}Nullam mollis nunc eu lorem mattis ac facilisis ligula suscipit. Integer imperdiet dolor adipiscing eros semper at rutrum lectus facilisis. Nam a urna justo. Aenean magna leo, rutrum dapibus facilisis quis, interdum nec lacus. {8}{9}Sincerly, {10}{11}{12}", DateTime.Now, Environment.NewLine, Environment.NewLine, sRecipientName, Environment.NewLine, Environment.NewLine, Environment.NewLine, Environment.NewLine, Environment.NewLine, Environment.NewLine, Environment.NewLine, Environment.NewLine, sSenderName));

For my initial pass through I did 3 runs with just creating the string once and outputting it to the console recording total memory usage and execution time. My results are as follows. Speed results are in seconds and memory results are in bytes.

First Pass on String Tests

As you can see from the above my results were a little under satisfying as they really didn’t answer my question one way or another. So I decided to take another run through of the three test cases, this time executing each one 100 times to give me a bigger picture on which one is faster. Here are my results:

Second Pass on String Tests

This second pass through offers a little bit more insight into the differences between the runs.

The tldr;

Straight string concatenation in this test was the fastest but also the biggest memory hog. The String Builder was the slowest but used up the least amount of memory on average. String.Format came in the middle of the two but also has the most difficult to understand code. So in the end it’s really comes down to what you are looking for. If you want the fastest performing go with string concatenation. For the lowest overhead go with a String Builder. Then if you want job security (because no one else can understand your code) go with String.Format for stats down the middle.

You can download the source for this test project here.

  4 Responses to “String.Format versus String Concatenation vs StringBuilder”

  1. Ever since you told me it would be beneficial to learn C# .NET, I’ve started browsing your blog to get some snippets and garnish understanding. I know you joke about String.Format being the hardest to understand, but to me, the String Builder is harder simply because of the break in format (needing to use the “sb.Append” syntax). Honestly, to me, the String.Format makes perfect sense – wherever there is a {#} within the text string simply correlates to the string of commands that follow the field.

    Maybe that is why Mrs. Cole back at South always got confused by my coding – as she would say, “It works beautifully and flawlessly, but I have no idea how you made it work.”

    There was also the, “Most people in coding think inside the box, some think outside the box, you deny the existence of the box and all other geometric shapes.”

    • Glad your enjoying reading around. I really need to update the site more, I have a good 6 or 7 articles I want to write all related to programming. I also have another project that I’ve been working on that i’m going to hopefully be announcing soon and linking to from here.

  2. Hi,

    nice article, but one question about method 2: Sometimes you append twice for newline, sometimes appendline and 1 newline. What if you use appendlines only?

    I created a string concatenator vs string builder for 10.000 passwords of 100 characters length. String concatenation uses 13 seconds to get the result, String builder 0.3 seconds

    Real difference is seen when using larger texts!

    Regards,

    Herman
    ps: like your article, nice input for a start

    • Thanks for catching that. I should have stuck to doing it one way or another. I’m not sure it would have any huge impact on performance but you never know.

      I may decide to revisit this article at some point in the future to try with longer strings.

      Thank you for your input and experiences.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.