String comparison performance in C#

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

    In my opinion, you should always use the clearest way, which is using ==!

    This can be understood directly: When "Hello" equals "World" then do something.

    if ("Hello" == "World")
        // ...
    

    Internally, String::Equals is invoked which exists explicitly for this purpose - Comparing two strings for equality. (This has nothing to do with pointers and references etc.)

    This here isn't immediately clear - Why compare to zero?

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

    .CompareTo isn't designed just for checking equality (you have == for this) - It compares two strings. You use .CompareTo in sorts to determine wheter one string is "greater" than another. You can check for equality because it yield zero for equal strings, but that's not what it's concepted for.

    Hence there are different methods and interfaces for checking equality (IEquatable, operator ==) and comparing (IComparable)

    Linq doesn't behave different than regular C# here.

提交回复
热议问题