Thursday, September 9, 2010

String vs Stringbuilder

Strings are mostly represented as values of the type String in C#.
If a string is initialized, it is not changeable anymore. Operations which work on Strings (as for example Replace() or Trim()), leave the original unchanged and create instead a copy which they then return.

To use changeable strings in .Net, we need the class StringBuilder. Instances of this class are created by the operator new and can dynamically be changed. Operations then work on the actual object:

StringBuilder DynamicString = new StringBuilder("Replace me");
DynamicString.Replace("Replace me""Replaced.");

DynamicString contains after the replacement the value "Replaced", as with a String this was not the case.
As you can see in the code, a string of type StringBuilder has to be explicitely converted to String, if a String is needed.

The technical details though are probably not that interesting, one very interesting feature of the class StringBuilder is its speed.
Generally, the processing of strings of the type String is pretty slow. If you for example read a text file and write its content to a String, this action takes some time.
The following code example appends 100000 times the wort "zeichenkette":

string OrdinaryString = "";
for (int i = 0; i < 100000; i++)
    OrdinaryString += "zeichenkette";

The program takes for execution on my laptop over a minute, using a string.
The same can be done using StringBuilder without noticeable time passing by!

StringBuilder BetterString = new StringBuilder();
for (int i = 0; i < 100000; i++)

When working with longer strings thus you should definitely use the class StringBuider, because an immense speedbost comes with that - but to be fair one has to also say, that String is more effective or short strings.
You can use the same trick, when writing longer texts in a TextBox. The property Text is also of the type String, so it can be more effective, to build the contents together using StringBuilder, and then assigning the whole to the textbox.

No comments:

Post a Comment