javablogspot

Just another WordPress.com weblog

Fun with Empty String.

Posted by damuchinni on February 25, 2009

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:

public bool IsEmpty_1(string text)

{

return text == “”;

}

public bool IsEmpty_2(string text)

{

return text.Equals(string.Empty);

}

public bool IsEmpty_3(string text)

{

return text.Length == 0;

}

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:

equality code

Here’s the result:

equality output

The result above compares empty string “” to “text”.

“text” == “”

“text”.Equals(“”)

“text”.Length == 0

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.

“” == “”

“”.Equals(“”)

“”.Length == 0

Here’s the output when comparing empty string with empty string.

equal output
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.

public static class StringUtils

{

public static bool IsEmpty(this string text)

{

return text.Length == 0;

}

}

Now we can write code like this:

“text”.IsEmpty();

We can go further and create extension methods like IsNull and IsNullOrEmpty:

public static bool IsNullOrEmpty(this string text)

{

return string.IsNullOrEmpty(text);

}

public static bool IsNull(this object obj)

{

return obj == null;

}

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?

string.IsNullOrEmpty(text);

text.IsNullOrEmpty();

One more note that IsNull extension method you can use with any object not just String.

List numbers;

if (numbers.IsNull())

….

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: