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
Thursday, 15 November 2007
Coding Tip 1 - Evil Strings
Posted by Joseph Megkousoglou at 13:37
Subscribe to:
Post Comments (Atom)
3 comments:
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?
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.
Post a Comment