What is the fastest (built-in) comparison for stri

2020-05-24 19:53发布

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 in order to search fast in large collections. I think there are only two methods: Compare and CompareOrdinal. What's the fastest?

Additionally, is there is a faster method for those string-comparisons?

8条回答
劫难
2楼-- · 2020-05-24 20:20

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

查看更多
乱世女痞
3楼-- · 2020-05-24 20:21

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

查看更多
欢心
4楼-- · 2020-05-24 20:21

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.

查看更多
等我变得足够好
5楼-- · 2020-05-24 20:22

I just noticed a 50% performance increase in my own code by comparing string lengths first and if equal then using the string.compare methods. So in a loop I have:

VB:

If strA.length = strB.length then
   if string.compare(strA,strB,true) = 0 then
      TheyAreEqual
   End if
End if

C#:

if(strA.Length == strB.Length)
{
   if(string.Compare(strA,strB,true) == 0)
   {
       //they are equal
   }
}

This could be dependant on your own strings but its seems to have worked well for me.

查看更多
够拽才男人
6楼-- · 2020-05-24 20:34

I'm assuming you want a less-than/equal/greater-than comparison rather than just equality; equality is a slightly different topic, although the principles are basically the same. If you're actually only searching for presence in something like a SortedList, I'd consider using a Dictionary<string, XXX> instead - do you really need all that sorting?

String.CompareOrdinal, or using an overload of String.Compare which allows the comparison to be provided, and specifying an ordinal (case-sensitive) comparison, e.g. String.Compare(x, y, StringComparison.Ordinal) will be the fastest.

Basically an ordinal comparison just needs to walk the two strings, character by character, until it finds a difference. If it doesn't find any differences, and the lengths are the same, the result is 0. If it doesn't find any differences but the lengths aren't the same, the longer string is deemed "larger". If it does find a difference, it can immediately work out which is deemed "larger" based on which character is "larger" in ordinal terms.

To put is another way: it's like doing the obvious comparison between two char[] values.

Culture-sensitive comparisons have to perform all kinds of tortuous feats, depending on the precise culture you use. For an example of this, see this question. It's pretty clear that having more complex rules to follow can make this slower.

查看更多
做自己的国王
7楼-- · 2020-05-24 20:38

Fastest is interned strings with reference equality test, but you only get equality testing and it's at the heavy expense of memory - so expensive that it's almost never the recommended course.

Past that, a case-sensitive ordinal test will be the fastest, and this method is absolutely recommended for non-culture-specific strings. Case-sensitive is faster if it works for your use case.

When you specify either StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase, the string comparison will be non-linguistic. That is, the features that are specific to the natural language are ignored when making comparison decisions. This means the decisions are based on simple byte comparisons and ignore casing or equivalence tables that are parameterized by culture. As a result, by explicitly setting the parameter to either the StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase, your code often gains speed, increases correctness, and becomes more reliable.

Source

查看更多
登录 后发表回答