Use String in other way in C#

In this post, I will show how you can optimize your string operations by using the StingBuilder class and the static class String.

string s1 = "Hello";
s1 = s1 + " world";
or equivalent

string s1 = "Hello";
s1 += " world";

So whats wrong with that. The problem is that a string is immutable: A string cannot change – it’s read-only. So the + operation does not change s1, but creates a new concated string, and then points s1 to the new strings location i memory. But the old string still lingers somewhere in the memory. And you string may be long, and you may append to it many times.
But how do we change a string, if a string is immutable. We don’t. We avoid creating the string until its completed, by keeping the  string in a StringBuilder until we are ready to copy the result to a real string. The StringBuilder is a mutable dynamic “string”. As a default, the builder holds 16 bytes of string data, but you can specify another length in the constructor – which you may want to do is you have an idea of how long the final string will be.

Actually, this is a pretty simple approach, not radical different that working with real strings:

using System.Text;

StringBuilder s1 = new StringBuilder();
s1.Append(“Hello”);
s1.Append(” world”);
Console.Write(s1.ToString());
A different, and less flexible approach is to use the static String.Concat method:

string s1 = String.Concat("Hello", " world");

0 comments: