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.
WRONG: if (string1.ToLower() == string2.ToLower()) //case insensitive string comparison
CORRECT: if (string.Compare(string1, string2, true) == 0) //case insensitive string comparison