String comparison performance in C#

后端 未结 10 1592
一向
一向 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:56

    I generally use String.Compare with the overload that takes a StringComparison parameter, because then I can be absolutely explicit about whether or not the comparison is case- and culture-sensitive. This needs .NET 2.0 or later.

    The fastest is StringComparison.Ordinal (or StringComparison.OrdinalIgnoreCase if case-insensitive) for comparisons that are not culture-sensitive.

    The problem with using == is that it's not clear that the author has considered case- and culture-sensitivity.

    There's a good MSDN article on the subject here.

提交回复
热议问题