Monday 13 July 2009

Three C# Performance boosting tips with strings!

From my short time of programming in C# i have seen some professional
developers using program structures that impact on performance,
when there is a faster alternative.

Tip 1

When comparing strings do not:

if (stringOne != stringTwo)
{
}

As that creates copy's of both variables, evaluates them and returns a result,
a better alternative is to use:

if (string.Compare(stringOne,stringTwo,false)==0)
{
}

This words directly with the string (remember instantiating a string is simply
creating an object from the String class...

Another benefit is that the third parameter corresponds to if it ignores the case
of the string's, thus saving the "stringOne.ToUpper()" syntax!

Tip 2

Do not assign strings magic data when in a loop, use the StringBuilder object to
stop the duplication of variables!

StringBuilder myString = new StringBuilder();
myString.Capacity = 10000;
for (int i = 0; i <>
{
myString.Append(i.ToString());
}

I done a small test against the conventional algorithm:

string myString = string.Empty;

for (int i = 0; i <>
{
myString += i.ToString();
}

The StringBuilder version gave me a result of 0.0038292 seconds while
the conventional method gave me a result of 0.3770280 seconds.

... That is 9746 times slower than the string builder.

Tip 3

The StringBuilder is fast but only when a loop with 100 > iterations is used!

I have seen developers use StringBuilder for concatenating 10 strings, that
is negativity impacting memory and CPU threads.




No comments:

Post a Comment