String comparison performance in C#

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

提交回复
热议问题