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

前端 未结 8 1522
南方客
南方客 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条回答
  •  闹比i
    闹比i (楼主)
    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..

提交回复
热议问题