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.

wpid-wpid-bulb1-2007-11-15-13-37-2007-11-15-13-37.jpgTip 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

Advertisements

2 thoughts on “Coding Tip 1 – Evil Strings

  1. >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?

  2. >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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s