Alex Rivera | Logout

Checking for string contents? string Length Vs Empty String

Asked 2008-08-13T19:03:27.683
20

Which is more efficient for the compiler and the best practice for checking whether a string is blank?

  1. Checking whether the length of the string == 0
  2. Checking whether the string is empty (strVar == "")

Also, does the answer depend on language?

Edit
Report

3 Answers

2

In .Net:

string.IsNullOrEmpty( nystr );

strings can be null, so .Length sometimes throws a NullReferenceException

answered 2008-08-13T19:05:54.197
2

For C strings,

if (s[0] == 0)

will be faster than either

if (strlen(s) == 0)

or

if (strcmp(s, "") == 0)

because you will avoid the overhead of a function call.

answered 2008-08-13T19:51:33.653
2

String.IsNullOrEmpty() only works on .net 2.0 and above, for .net 1/1.1, I tend to use:

if (inputString == null || inputString == String.Empty)
{
    // String is null or empty, do something clever here. Or just expload.
}

I use String.Empty as opposed to "" because "" will create an object, whereas String.Empty wont - I know its something small and trivial, but id still rather not create objects when I dont need them! (Source)

answered 2008-08-14T11:26:53.060

Your Answer