Why is String.IsNullOrEmpty faster than String.Length?

前端 未结 7 2056
心在旅途
心在旅途 2020-12-14 17:28

ILSpy shows that String.IsNullOrEmpty is implemented in terms of String.Length. But then why is String.IsNullOrEmpty(s) faster than

7条回答
  •  离开以前
    2020-12-14 17:51

    I believe your test is not correct:

    This test shows that string.IsNullOrEmpty is always slower than s.Length==0 because it performs an additional null check:

    var strings = "A,B,,C,DE,F,,G,H,,,,I,J,,K,L,MN,OP,Q,R,STU,V,W,X,Y,Z,".Split(',');
    var testers = new Func[] { 
        s => s == String.Empty, 
        s => s.Length == 0, 
        s => String.IsNullOrEmpty(s), 
        s => s == "" ,
    };
    int n = testers.Length;
    var stopwatches = Enumerable.Range(0, testers.Length).Select(_ => new Stopwatch()).ToArray();
    int count = 0;
    for(int i = 0; i < n; ++i) { // iterate testers one by one
        Stopwatch sw = stopwatches[i];
        var tester = testers[i];
        sw.Start();
        for(int j = 0; j < 10000000; ++j) // increase this count for better precision
            count += strings.Count(tester);
        sw.Stop();
    }
    for(int i = 0; i < testers.Length; i++)
        Console.WriteLine(stopwatches[i].ElapsedMilliseconds);
    

    Results:

    6573
    5328
    5488
    6419
    

    You can use s.Length==0 when you are ensure that target data does not contains null strings. In other cases I suggest you use the String.IsNullOrEmpty.

提交回复
热议问题