为什么string.IsNullOrEmpty比比较快?

时间:2013-08-29 09:54:33

标签: c# performance

MS Analyzer建议使用string.IsNullOrEmpty代替使用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");
    }
}

2 个答案:

答案 0 :(得分:13)

  

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

     

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

只需read the fine manual

  

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

     

...

     

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

     

...

     

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

您的问题不是null检查,而是使用空Equals实例测试相等(通过string),而不是检查其Length。< / p>

再次,从精细的手册:

  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.");
     }
  }

答案 1 :(得分:2)

IsNullOrEmpty将被内联,因此将避免调用该方法的开销。查看该方法,它使用属性

进行修饰
[__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]

我还补充说,从可读性的角度来看,IsNullOrEmpty更清晰,更具描述性(在我看来)。

至于表现,如果您使用value.Length == 0;代替x == "",我会感到惊讶。在内部,IsNullOrEmpty执行此操作

return value == null || value.Length == 0;

if (x == null || x == "")

读取属性所需的开销比计算相等性要少。