Faster string comparisons with CompareOrdinal

You can compare strings in many ways under VB.NET: by using the = operator (or another comparison operator), with the Equals method (which the String class inherits from System.Object), or with the Compare shared method. The Compare method is especially useful because it returns an integer that tells whether the first string is less (-1), equal (0), or higher (+1) than the second string. This feature lets you perform only one comparison and use the result in a Select Case block:

Select Case String.Compare(first, second)    Case -1        Console.WriteLine("{0} is less than {1}", first, second)    Case 0        Console.WriteLine("{0} is equal to {1}", first, second)    Case 1        Console.WriteLine("{0} is higher than {1}", first, second)End Select

The only problem with the Compare method is that it compares strings in a local-aware fashion, so it has to convert the Unicode code of each character into a numeric value that reflects its position in the current culture’s alphabet. For example, the Compare method considers the “b” lowercase character to come immediately after the “A” uppercase char and before the “B” uppercase char, even though the “A” and “B” characters are contiguous in the Unicode character set. This conversion activity takes time and consume CPU cycles, so you’ll find that VB.NET is less efficient than VB6 at comparing strings. Using the = operator and other comparison operators doesn’t help at all, because they map to the Compare method behind the scenes, so these operators suffer from the same performance loss.

If you are only interested in checking whether two strings contain the same characters (in a case-sensitive comparison), you can speed up your code by using the CompareOrdinal shared method. This method is 3-4 times faster than the Compare method (or the = operator) because it just scans the two strings and compare the Unicode numeric code of each character:

If String.CompareOrdinal(first, second) = 0 Then    Console.WriteLine("The two strings are equal")Else    Console.WriteLine("The two strings are different")End If

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: