What is the fastest (built-in) comparison for string-types in C#

前端 未结 8 1521
南方客
南方客 2021-02-05 02:09

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

相关标签:
8条回答
  • 2021-02-05 02:43

    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..

    0 讨论(0)
  • 2021-02-05 02:44

    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

    0 讨论(0)
提交回复
热议问题