My blog has moved!

You should be automatically redirected in 6 seconds. If not, visit
http://www.csharpblog.net/
and update your bookmarks.

Thursday 15 November 2007

Coding Tip 1 - Evil Strings

Starting today I will be posting a weekly coding tip that will hopefully help us all avoid common mistakes and errors.

Tip 1 – Evil Strings (Avoid Unnecessary String Creation)

Avoid creating strings unnecessarily. When converting strings to upper or lowercase, cache the result where necessary rather than duplicating a previous string creation. Prefer string.Compare over converting strings to upper or lowercase when performing case-insensitive comparisons. Do not create strings that are not subsequently assigned to variables. Unnecessary string creation degrades performance.

Example:

WRONG: if (string1.ToLower() == string2.ToLower()) //case insensitive string comparison

CORRECT: if (string.Compare(string1, string2, true) == 0) //case insensitive string comparison

3 comments:

Den Odell said...

Thanks, Joe. I've been doing it the wrong way for a while now!

Any idea on the performance improvement you get on this method? is it dramatic or just one of those things that accumulates the more you use it on a page?

Joseph Megkousoglou said...

It is an accumulative thing really - the more you use the worse it gets. Bare in mind that .NET does not destroy objects immediately so you might have tons of string objects lying about until GC kicks in.

chanel said...
This comment has been removed by a blog administrator.