Wednesday, February 6, 2008

String silliness

Yesterday at work, Carlos and I had a silly converstation about the best way to check if a trimmed string is NULL or EMPTY.

I usually do this:

if (string.IsNullOrEmpty(x) x.Trim().Length == 0)


Carlos liked this better because its prettier:

if (x == null || x.Trim().Length == 0)

Of course, I took offense to that because I find my version to be quite attractive as well. So, instead of settling on which one is prettier, we broke it down into basic operations to see which one would be (theoretically) quicker.

In most cases, x will be a valid string.

string x = "123";
if (string.IsNullOrEmpty(x) || x.Trim().Length == 0)

1 - Check for null
2 - Check for empty (.Length == 0)
3 - Trim the string
4 - Check the length
Under normal circumstances, there are 4 things to do


string x = "123";
if (x == null || x.Trim().Length == 0)

1 - Check for null
2 - Trim
3 - Check the length
Under normal circumstances, there are 3 things to do.

So, the second choice is the better one, and we will use that going forward.

Out of curiosity, I took a look at the string source code to see how it was doing some things.


if (x.Trim().Length == 0)
or
if (x.Trim() == string.Empty)


.Length has been my means of choice. Its just a property value as opposed to a comparison. The string source code does it the same way.


System.String.IsNullOrEmpty()
if (value != null) { return value.Length == 0;} return true;

I think we've made a lot of progress towards solving some insignificant problems. Super.

2 comments:

Mike said...

So silly question, why dont you use string.isnullorempty in the first place?

Anonymous said...

Didn't see this comment... i added a related comment to the other post.

Anyway:

string x = null;
string.IsNullOrEmpty(x.Trim());

Boom! You can't call methods on a null.