Small Tip: C# Strings are immutable

One small thing a lot of newcomers to C# and .Net in general are not aware of, is that Strings are immutable. What does that mean? That means a string you created cannot be altered. Strings can only be created and destroyed

What does that mean for the novice programmer?
Well let’s look at a small example of code.

Now everyone knows that the output of this snippet will be a string that 10000 times the character a.
But what happenes underneath?
Well given that strings are immutable each time the addition of the character a in the string is in fact creating a new string with an extra character in it. So in the end of the day, this small loop will create 10 000 string variables, all of them except the last one are thrown in the garbage. Memory allocation is in fact a lengthy process and the code snippet above is actually wasting a lot of resources (both memory and computational time).

The above code snippet could be re-implemented using StringBuilder class in the following way.

The above snippet is in fact creating only one string at the end of the loop instead of so many. This greatly improves performance and memory consumption.

Leave a Reply