性能 - str_01 == str_02 vs(对象)str_01 ==(对象)str_02

Moh*_*deh 2 c# string performance string-interning

在下面的代码示例中是否有任何性能优化,我比较两个字符串?

第一:

public static bool Compare_01()
{
    string str_01 = "a";
    string str_02 = "a";

    if (str_01 == str_02)
        return true;
    else
        return false;
}
Run Code Online (Sandbox Code Playgroud)

二:

public static bool Compare_02()
{
    string str_01 = "a";
    string str_02 = "a";

    if ((object)str_01 == (object)str_02)
        return true;
    else
        return false;
}
Run Code Online (Sandbox Code Playgroud)

他们两个都回来了true.

他们的il代码只有一个不同:

第一名:

IL_0001:  ldstr       "a"
IL_0006:  stloc.0     // str_01
IL_0007:  ldstr       "a"
IL_000C:  stloc.1     // str_02
IL_000D:  ldloc.0     // str_01
IL_000E:  ldloc.1     // str_02
IL_000F:  call        System.String.op_Equality
Run Code Online (Sandbox Code Playgroud)

第二:

IL_0001:  ldstr       "a"
IL_0006:  stloc.0     // str_01
IL_0007:  ldstr       "a"
IL_000C:  stloc.1     // str_02
IL_000D:  ldloc.0     // str_01
IL_000E:  ldloc.1     // str_02
IL_000F:  ceq         
Run Code Online (Sandbox Code Playgroud)

我在System.String中发现了类似的东西:

public static bool Equals(String a, String b) {
    // Here
    if ((Object)a==(Object)b) {
        return true;
    }
    // ****

    if ((Object)a==null || (Object)b==null) {
        return false;
    }

    if (a.Length != b.Length)
        return false;

    return EqualsHelper(a, b);
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 7

您的版本"Two"做了不同的事情:它比较了参考相等性(您可以ceq在编辑中添加的IL中看到这一点).由于字符串实习,这通常可以在基本测试中使用 - 但不应该依赖它.它只是意外工作.

基本上,只需使用:

return str_01 == str02;
Run Code Online (Sandbox Code Playgroud)

这是表达"比较这两个字符串以求平等"的惯用方式,string.Equals(string a, string b) 无论如何它都将被内联到一个调用中.