String Comparison
437 words.
There are a bunch of different ways to compare two strings in .NET. Periodically I ponder which one is “the best.” As with most things in programming, it’s largely a personal preference.
Assume we have two strings.
string x, y;
Ideally, to compare them, we just do this:
if( x == y ) FoundMatch();
It’s readable and easy to understand. If the strings are equal, it’s a match. What could be simpler? Unfortunately, it happens to be case sensitive comparison, so “Tom” won’t match “tom.” Often times we need a case-insensitive string comparison, and that’s where we need to be a little more creative. There are a lot of different solutions, the most basic being:
if( x.ToLower() == y.ToLower() ) FoundMatch();
That’s also easy to read and understand. It’s self-evident (to me, at least) that this is intended to be a case-insensitive string comparison. Unfortunately, it’s also the least efficient way to perform the task, in terms of memory and processing cycles. Two new string objects need to be created and garbage collected. If the comparison isn’t in an area of code that’s time sensitive, it probably doesn’t matter. But if you’re looking for optimal performance, here’s another, more efficient method:
if( string.Compare( x, y, true ) == 0 ) FoundMatch();
The “true” parameter indicates a case-insensitive comparison. Unfortunately, it’s not self-evident what the software is doing when looking at the code. It’s obviously a string comparison, but what kind? You have to add a comment or know what the “true” parameter means to understand it. So, while it is much better performance-wise, it’s not as good maintenance-wise.
In .NET 2.0, we get a few new options. Here’s one:
if( x.Equals( y, StringComparison.OrdinalIgnoreCase ) ) FoundMatch();
The OrdinalIgnoreCase comparison is optimized specifically for fast, non-cultural string comparisons, and it tells you exactly what it’s doing. But this is where personal preference comes into play: At this point in my programming career, I think the x.Equals(y) syntax looks funny. The good news is we get one more option in .NET 2.0:
if( string.Compare( x, y, StringComparison.OrdinalIgnoreCase ) == 0 ) FoundMatch();
I like this one best. While it is the longest in terms of typing, it’s easy to understand and good for performance. It’s obvious that you are comparing two strings (“string.Compare”) and it’s obvious that it’s supposed to be case-insensitive (“OrdinalIgnoreCase”), and it also happens to use one of the most efficient methods of comparing strings in .NET. A win-win situation all around.
If you need to be culture-sensitive in your string comparisons, you have a whole different set of challenges. I’ll leave that for another day.
Sorry, new comments are disabled on older posts. This helps reduce spam. Active commenting almost always occurs within a day or two of new posts.