Showing posts with label How many strings are allocated in each of the code snippets below?. Show all posts
Showing posts with label How many strings are allocated in each of the code snippets below?. Show all posts

Monday, March 29, 2010

How many strings are allocated in each of the code snippets below?

VisualBasic Code Snippet
Dim s As String

s = "how"
s += " many"
s += " strings"
s += " are"
s += "allocated?"
Console.WriteLine(s)

C# Code Snippet
string s;

s = "how";
s += " many";
s += " strings";
s += " are";
s += "allocated?";
Console.WriteLine(s);


If you said one string was allocated, then... you are wrong. Five strings are actually allocated. Strings in the .NET framework are immutable. This means that each change the string s causes the runtime to create a new string and abandon the old one. The immutable nature of .NET strings should be considered when performance is a concern. The creation of temporary strings can be avoided using two methods:

  • Use the String classes Concat, Join or Format methods to join multiple in a single statement
  • Use the StingBuilder class to create dynamic (mutable) strings

Additional Resources
String class (Microsoft)
StringBuilder class (Microsoft)