Thursday, 29 August 2013

Why is string.IsNullOrEmpty faster than comparison?

Why is string.IsNullOrEmpty faster than comparison?

MS Analyzer recommends to use string.IsNullOrEmpty instead of comparising
it either with null or empty string for performance reasons
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");
}
}

No comments:

Post a Comment