What is the fastest built-in comparison-method for string-types in C#? I don\'t mind about the typographical/semantical meaning: the aim is to use the comparator in sorted lists
I Checked both the string.Compare and string.CompareOrdinal using stop watch
--Compare Ordinal case 1
Stopwatch sw = new Stopwatch();
sw.Start();
int x = string.CompareOrdinal("Jaswant Agarwal", "Jaswant Agarwal");
sw.Stop();
lblTimeGap.Text = sw.Elapsed.ToString();
-- Only compare case 2
Stopwatch sw = new Stopwatch();
sw.Start();
int x = string.Compare("Jaswant Agarwal", "Jaswant Agarwal");
sw.Stop();
lblTimeGap.Text = sw.Elapsed.ToString();
In case 1 Average elapsed timing was 00:00:00.0000030 In case 2 Average elapsed timing was 00:00:00.0000086
I tried with different Equal and not equal combinations of string and found that every time CompareOrdinal is faster than only compare..
That is my own observation..you can also try just put two buttons on a form and copy paste this code in regrading event..
This is quite an old question, but since I found it others might as well.
In researching this topic a bit further, I came upon an interesting blog post that compares all methods for string comparison. Probably not highly scientific but still a good housenumber.
Thanks to this article I started using string.CompareOrdinal in a scenario where I had to find out if one string was in a list of 170.000 other strings and doing this 1600 times in a row. string.CompareOrdinal made it almost 50% faster compared to string.Equals