Thursday, January 21, 2010

Use StringBuilder Class instead of String Class when you manipulate string object

Use System.Text.StringBuilder Class instead of System.String Class when you have to manipulate string objects in a loop. Each time you append a string object in a loop it is actually discarding the old string object and recreating a new one which is relatively expensive operations.

Have a look at the following example where the string object ‘message’ is discarded each time.

public string MyMessage(string[] lines)
{
string message = String.Empty;
for(int i=0;i<lines.length;i++)
{
message+=lines[i];
}
return message;
}

The System.String Class object is immutable. Every time you use System.String Class, you create a new string object in memory. In situations where you need to perform repeated modifications to a string object, the overhead associated with creating a new string object can be costly. The System.Text.StringBuilder Class can be used when you want to modify a string object without recreating a new one. Using the System.Text.StringBuilder Class can boost performance when concatenating many string objets together in a loop.

Have a look at the following example where the System.String Class object is replaced with the System.Text.StringBuilder Class.

public string MyMessage(string[] lines)
{
StringBuilder message =new StringBuilder();
for(int i=0;i<lines.length;i++)
{
Message.Append(ines[i]);
}
return message;
}

That’s it.

No comments:

Post a Comment

Related Posts with Thumbnails