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

前端 未结 8 1657
南方客
南方客 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:35

    This might be useful to someone, but changing one line of my code brought the unit testing of my method down from 140ms to 1ms!

    Original

    Unit test: 140ms

    public bool StringsMatch(string string1, string string2)
    {
        if (string1 == null && string2 == null) return true;
        return string1.Equals(string2, StringComparison.Ordinal);
    }
    

    New

    Unit test: 1ms

    public bool StringsMatch(string string1, string string2)
    {
        if (string1 == null && string2 == null) return true;
        return string.CompareOrdinal(string1, string2) == 0 ? true : false;
    }
    

    Unit Test (NUnit)

    [Test]
    public void StringsMatch_OnlyString1NullOrEmpty_ReturnFalse()
    {
        Authentication auth = new Authentication();
        Assert.IsFalse(auth.StringsMatch(null, "foo"));
        Assert.IsFalse(auth.StringsMatch("", "foo"));
    }
    

    Interestingly StringsMatch_OnlyString1NullOrEmpty_ReturnFalse() was the only unit test that took 140ms for the StringsMatch method. StringsMatch_AllParamsNullOrEmpty_ReturnTrue() was always 1ms and StringsMatch_OnlyString2NullOrEmpty_ReturnFalse() always <1ms.

提交回复
热议问题