String comparison performance in C#

后端 未结 10 1591
一向
一向 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 12:03

    If the equality operator actually performed worse than CompareTo - wouldn't Microsoft make the implementation of the equality operator call CompareTo?

    Just use the equality operator to test for equality.

    0 讨论(0)
  • 2020-12-20 12:08

    There was a pretty similar question recently regarding the fastest way to trim a string, but it was basically benchmarking the different ways of comparing them.

    You can check out the benchmarks on this post.

    0 讨论(0)
  • 2020-12-20 12:08

    Here is the most complete and helpful MSDN guide for string comparison I have found.

    Use comparisons with StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase for better performance.

    0 讨论(0)
  • 2020-12-20 12:10

    Read Jeff’s The Best Code is No Code at All. foo.CompareTo(bar) == 0: horrible visual clutter. Takes up a lot of space and conveys no interesting meaning. In fact, it emphasizes a lot of irrelevant stuff which deflects attention away from the real problem.

    If there’s no well-defined reason for using this longer variant, don’t.

    As for performance: it simply doesn’t matter for this simple case. If the equality operator == should really perform worse than CompareTo, feel free to file a bug report with Microsoft. This must not happen.

    0 讨论(0)
提交回复
热议问题