From the files of the “never stop learning” department comes a cautionary lesson in performance, courtesy of this blogger.
Often times when you’re comparing strings you want to eliminate case differences from consideration. Some people use ToUpper(), some use ToLower(), and both are equally valid for that goal. So what’s wrong with the following code (other than the fact that it doesn’t do anything useful)?
if(student.FirstName.ToLower() == “ebenezer”)
System.Console.WriteLine(“Sucks to be that kid”);
By itself there’s probably nothing worth addressing. But what if we zoom out a little?
foreach(Student student in schoolStudents)
if(student.FirstName.ToLower() == “mortimer”)
System.Console.WriteLine(“His parents must hate him”);
Enough suspense. The problem here is that strings are immutable, or unchangeable. That means if you change a string in any way you’re actually creating a new string instance and disposing of the original. That’s exactly what’s happening each time you call .ToLower() on the FirstName string property of the student. Not such a big deal in the first example but potentially a very big deal in the second. If there are 1,000 students in the schoolStudents collection, you’re creating 1,000 extra string instances just for comparing the values – to say nothing of what else you might do inside the if block!
How can you avert this tragic miscarriage of optimization? Easy. Replace the ToLower() line with the following:
// do something
The author of the original link ran several test iterations and found that performance is roughly 3 times better with Equals() than it is with ToLower()!
It’s good to go back and revisit concepts that are tempting to dismiss as too elementary. It helps keep the “programmer’s ego” in check and helps solidify your foundation as a competent and skilled professional.