Friday, February 29, 2008

[.NET] Strings gone wild

Are .NET strings evil? Not at all, but there is an exception to this: where in big packs strings can become very dangerous for performance of your app. Let's see why and how to avoid this.

System.String is a reference type implemented to behave as a value type; Strings instances of this type are IMMUTABLE : When a string is created if you modify it a new one is created and the old one is abandoned to the care of the garbage collector. For example with the following code we are creating 3 strings not just one, and we're keeping a reference to the last one that's been created:
string mySillyString = "hey";
mySillyString += " hey ";
mySillyString += " hey!";

This is fine if you are doing just a few of these operations, but if you are going down with massive string manipulation (maybe within loops), all the overhead associated with the string creation will cause your app to slow down, plus all the abandoned strings will pack together and go wild, giving an hard time to the garbage collector, and eventually feckin'up you app performances.

In such a case we should use a way to operate on strings dinamically. Without using any unsafe block of code, we can easily do this trying to use when possible string methods like Join, Concat and Format (the latter - as we all know - very useful). But the real rock star here is the StringBuilder: it sure carries a bit of overhead, so it might not worth it to use it just for a few string manipulations, but if you plan to do more than 10 operations you should use it as a rule. In case of fast machines, even more than 5 operations might justify the use of a string builder (as indicated on this MSDN paper: ).
Here an example of how to use the StringBuilder:

System.Text.StringBuilder myKickAssStringBuilder = new
myKickAssStringBuilder.Append("hey ");
myKickAssStringBuilder.Append(" hey ");
myKickAssStringBuilder.Append(" hey!");
myKickAssStringBuilder.Append(" hey Stoopid");
string myLonelyString = myKickAssStringBuilder.ToString();

All for today. Kick-Ass out there.

No comments: