String comparison performance in C#

后端 未结 10 1649
一向
一向 2020-12-20 11:42

There are a number of ways to compare strings. Are there performance gains by doing one way over another?

I\'ve always opted to compare strings like so:



        
10条回答
  •  太阳男子
    2020-12-20 11:43

    According to Reflector

    "Hello" == "World"
    

    is the same as

    String.Equals("Hello", "World");
    

    which basically determines if they are the same reference object, if either of them is null, which would be an automatic false if one was null and the other was not, and then compares each character in an unsafe loop. So it doesn't care about cultural rules at all, which usually isn't a big deal.

    and

    "Hello".CompareTo("World") == 0
    

    is the same as

    CultureInfo.CurrentCulture.CompareInfo.Compare("Hello", "World", CompareOptions.None);
    

    This is basically the opposite as far as functionality. It takes into consideration culture, encoding, and everything else with the string in to context.

    So I would imagine that String.CompareTo is a couple of orders of magnitude slower than the equality operator.

    as for your LINQ it doesn't matter if you are using LINQ-to-SQL because both will generate the same SQL

    var results = from names in ctx.Names
              where names.FirstName.CompareTo("Bob Wazowski") == 0
              select names;
    

    of

    SELECT [name fields]
    FROM [Names] AS [t0]
    WHERE [t0].FirstName = @p0
    

    so you really aren't gaining anything for LINQ-to-SQL except harder to read code and probably more parsing of the expressions. If you are just using LINQ for standard array stuff then the rules I laid out above apply.

提交回复
热议问题