String vs. StringBuilder

A blog would not be complete without an article about the differences between appending or modifying a string using the String Class versus the StingBuilder class. See, strings are immutable, which means once they are created they cannot be changed. Any time you make a modification to a string, after is has been created you are actually creating a new string object in memory. Each time you use one of these methods, you will create a new string object in memory. What this means is that when you write a program that will modify a lot of strings, I mean a lot of strings, then using the StringBuilder class will drastically improve performance. If you are only going to create a string an modify it 5, 10, 100 times, keep it simple and use the String Class.

There are a lot of articles about this topic, but I wanted to write my own because I learn from writing things down and repeating things over and over again.

I wrote a test to show the difference in speed between the 2. Up to about 5000 iterations, there was really no difference between the String Class and StringBuilder. However, when you begin to grow over 10000, 25000, 50000 or 100000, then you really begin to see the difference. See below

image

As you can see, the more you process the longer it takes the string class to complete, but the StringBuilder takes no time at all. I had to change my code to use minutes instead of seconds to get the 100,000 test to show up right. You see, there is significant differences.

In this post you learned about mutable versus immutable objects and what impact they have on performance and memory utilization.

Download the source.



1 Comment

 Add your comment
  1. Thank you for this very interesting example. I don’t understand why Microsoft does not modify its C# compiler to implement strings as StringBuilders. Are there other characteristics of StringBuilders that make them less interesting than strings ?

Leave a Comment

Your email address will not be published.