String concatenation VS StringBuilder append

I often hear people claim that using string concatenations inside loops comes with a huge penalty given the performance. Usually no one knows exactly how much this penalty is; so I decided to measure it.

For this I created a very simple application, that keeps adding the string representation of the current iteration to the end of a String/StringBuilder, with the number of words increasing incrementally from 1 to a million. Actually, I am biased toward Strings, because I think they create cleaner and more readable code than StringBuilders. Having said that, let’s see how my tests performed. Here are the results:

String concat for 1 substrings: 0 millisecs.
StringBuilder concat for 1 substrings: 0 millisecs.

String concat for 10 substrings: 0 millisecs.
StringBuilder concat for 10 substrings: 0 millisecs.

String concat for 100 substrings: 1 millisecs.
StringBuilder concat for 100 substrings: 0 millisecs.

String concat for 1,000 substrings: 3 millisecs.
StringBuilder concat for 1,000 substrings: 0 millisecs.

String concat for 10,000 substrings: 179 millisecs.
StringBuilder concat for 10,000 substrings: 1 millisecs.

String concat for 100,000 substrings: 18635 millisecs.
StringBuilder concat for 100,000 substrings: 2 millisecs.

String concat for 1,000,000 substrings: 2919877 millisecs. //Well, this is more than 48 minutes… Sweet.
StringBuilder concat for 1,000,000 substrings: 24 millisecs.

In conclusion, in case of a loop with a thousand iterations makes no relevant difference with regard to runtime; above that threshold, however, it is not worth using Strings. I can hardly imagine such a huge String concat loop, though in production environments.

I have to say that the difference in the last case surprised me a lot; 48 minutes compared to 24 milliseconds, this is shocking (of course this is not a realistic example, I only included it for fun. Waiting for the app to terminate, however, was not funny at all).

That’s it, mystery solved.

Advertisements

Author: tamasgyorfi

Senior software engineer, certified enterprise architect and certified Scrum master. Feel free to connect on Twitter: @tamasgyorfi

One thought on “String concatenation VS StringBuilder append”

  1. It’s actually a cool and useful piece of information. I’m happy that
    you just shared this helpful info with us. Please keep us up to date like
    this. Thank you for sharing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s