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;
}
{
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;
}
{
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