Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is string.IsNullOrEmpty faster than comparison? [duplicate]

Tags:

performance

c#

MS Analyzer recommends to use string.IsNullOrEmpty instead of comparising it either with null or empty string for performance reasons

Warning 470 CA1820 : Microsoft.Performance : Replace the call to 'string.operator ==(string, string)' in ... with a call to 'String.IsNullOrEmpty'.

Why is that? Shouldn't the requirement to call another function and pass it reference to some object, which then needs to execute some kind of comparison anyway, be more expensive than executing comparison itself?

Example code

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");
    }
}
like image 334
Petr Avatar asked Aug 29 '13 09:08

Petr


1 Answers

MS Analyzer recommends to use string.IsNullOrEmpty instead of comparising it either with null or empty string for performance reasons

Warning 470 CA1820 : Microsoft.Performance : Replace the call to 'string.operator ==(string, string)' in ... with a call to 'String.IsNullOrEmpty'.

Just read the fine manual:

A string is compared to the empty string by using Object.Equals.

...

Comparing strings using the String.Length property or the String.IsNullOrEmpty method is significantly faster than using Equals. This is because Equals executes significantly more MSIL instructions than either IsNullOrEmpty or the number of instructions executed to retrieve the Length property value and compare it to zero.

...

To fix a violation of this rule, change the comparison to use the Length property and test for the null string. If targeting .NET Framework 2.0, use the IsNullOrEmpty method.

Your problem is not so much the null check, but instead testing for equality (via Equals) with an empty string instance rather than checking its Length.

Again, from the fine manual:

  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.");
     }
  }
like image 168
ta.speot.is Avatar answered Oct 25 '22 04:10

ta.speot.is