I am faster.
Everyone uses pretty heavily IsNullOrEmpty function that is a member of String class. But sometimes we need to implement different behavior for an Empty value versus the null one. There are multiple ways we can check for an Empty value.
Here are three different ways I come up with:
After looking at these functions in Reflector, it was obvious that the method that uses Length should be the most efficient. To prove it I created a little Console application that executes each comparison 100,000,000 times. Here’s the code that does it:
Here’s the result:
The result above compares empty string “” to “text”.
You can see that statement with equality operator (==) executes slower than the one with Equals function. However if we compare empty string with empty string we would have different result.
Here’s the output when comparing empty string with empty string.
I am more readable.
Efficient code is important but I would chose the most readable code. Unfortunately we cannot prove with numbers which code is more readable. It can be very subjective which code is easier to read but in any case I’ll be brave enough and make my recommendations.
I would extend String class with extension method.
Now we can write code like this:
We can go further and create extension methods like IsNull and IsNullOrEmpty:
You probably think why do we need to extend with IsNullOrEmpty; it’s already part of String class. You don’t but I think it’s more readable. Look at two statements bellow. Which one makes more scenes to you?
One more note that IsNull extension method you can use with any object not just String.