为什么string.IsNullOrEmpty比比较快?

Pet*_*etr 15 c# performance

string.IsNullOrEmpty出于性能原因,MS Analyzer建议使用null或空字符串进行比较

警告470 CA1820:Microsoft.Performance:通过调用'String.IsNullOrEmpty'替换对'string.operator ==(string,string)'的调用.

这是为什么?不应该要求调用另一个函数并将它传递给某个对象,然后需要执行某种比较,这比执行比较本身要贵吗?

示例代码

void Foo()
{ // throws a warning
    string x = "hello world";
    if (x == null || x == "")
    {
        Console.WriteLine("Empty");
    }
}

void Foo()
{ // doesn't throw it
    string x = "hello world";
    if (string.IsNullOrEmpty(x))
    {
        Console.WriteLine("Empty");
    }
}
Run Code Online (Sandbox Code Playgroud)

ta.*_*.is 14

出于性能原因,MS Analyzer建议使用string.IsNullOrEmpty而不是使用null或空字符串对其进行比较

警告470 CA1820:Microsoft.Performance:通过调用'String.IsNullOrEmpty'替换对'string.operator ==(string,string)'的调用.

只需阅读精细手册:

使用Object.Equals将字符串与空字符串进行比较.

...

使用String.Length属性或String.IsNullOrEmpty方法比较字符串要比使用Equals快得多.这是因为Equals执行的MSIL指令要比IsNullOrEmpty或执行的指令数量多得多,以检索Length属性值并将其与零进行比较.

...

要修复违反此规则的情况,请更改比较以使用Length属性并测试空字符串.如果以.NET Framework 2.0为目标,请使用IsNullOrEmpty方法.

你的问题不是null检查,而是Equals用空string实例测试相等(via )而不是检查它Length.

再次,从精细手册:

  public void EqualsTest()
  {
     // Violates rule: TestForEmptyStringsUsingStringLength. 
     if (s1 == "")
     {
        Console.WriteLine("s1 equals empty string.");
     }
  }

  // Use for .NET Framework 1.0 and 1.1. 
  public void LengthTest()
  {
     // Satisfies rule: TestForEmptyStringsUsingStringLength. 
     if (s1 != null && s1.Length == 0)
     {
        Console.WriteLine("s1.Length == 0.");
     }
  }
Run Code Online (Sandbox Code Playgroud)