9

Which one is better among these three?

string myString = ""; 
String.IsNullOrEmpty(myString);

vs

string myString = "";
if(myString.Length > 0 || myString != null)

vs 

string myString = "";
if (m.Length > 0 | m != null)

Former is clearer but is there any performance difference among these? What if, in case a string is never empty, like if taken from a Text Box, which could be empty but not null ?

7 Answers 7

19

Well, the version in the question:

if(myString.Length > 0 || myString != null)

would definitely be worse, as you should test for null first (not second) - ideally short-circuiting on null so you don't attempt to call .Length. But generally I'd just use string.IsNullOrEmpty. You could always write an extension method to make it less verbose if you want (you can call extension methods on null values).

static bool HasValue(this string s) {
    return !string.IsNullOrEmpty(s);
}
Sign up to request clarification or add additional context in comments.

11 Comments

Yeah, nice tip that last one. I am a bit of a sucker for string.Format extension methods :)
Great one always, never thought about it.
@Marc Gravell: I realize the method is static, but when calling it on an instance variable not everyone may be able to tell if such call will throw a null reference exception or not.
I agree with Esteban, the syntax is not 100% clear to the uninitiated. In an attempt to make this clearer, instead of naming the extension method 'HasValue' I would instead name it exactly the same as the static method: 'IsNullOrEmpty', which is allowed: public static bool IsNullOrEmpty(this string s) { return string.IsNullOrEmpty(s); }
@Z280Z28: No, that's not right. You should never throw a 'NullReferenceException' in your own code. Extension methods are static methods and therefore should throw an 'ArgumentNullException' (if you are going to throw one -- the examples here should return true or false and not throw). For more on this see: stackoverflow.com/questions/463302/….
|
4

Go with string.IsNullOrEmpty(str). It's clearer and more succinct. It will not be a bottle-neck in your application.

If you only need to check for string "emptiness", then I would go with a check against string.Empty since it expresses your intent better.

Comments

2

I'd use the IsNullOrEmpty.

It will be easier to parse when you are looking through the code later on.

Here's another - slightly bizarre - reason. Some later programmer is bound to come along later, scratch his beard and say "I think that myString.trim().Length != 0 is better" and change it.

As others have pointed out: checking for null second is a potential null access error waiting to happen - the library routine is guaranteed to be ok.

1 Comment

Hence the creation of IsNullOrWhitespace: msdn.microsoft.com/en-us/library/…
2

As others have said, IsNullOrEmpty() is superior to the manual checks for purposes of maintainability and isn't likely to suffer in performance thanks to the JIT compiler's runtime decisions about inlining (see Eric Gunnerson's comments).

In case anyone else is wondering what the actual .NET implementation looks like, here is the .NET 4 code:

[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static bool IsNullOrEmpty(string value)
{
    if (value != null)
    {
        return (value.Length == 0);
    }
    return true;
}

That attribute indicates the method will also be inlined in NGen (that is, native) images.

1 Comment

Interesting, ILSpy.exe shows that mscorlib -> System -> String -> IsNullOrEmpty(string): bool looks like this: return value == null || value.Length == 0;.
1

The String.IsNullOrEmpty is the better choise if you are unsecure about how to test the different states of the string reference (which you obviously are, as you got it wrong... ;).

Using the IsNullOrEmpty method:

if (String.IsNullOrEmpty(s)) ...

is equivalent to using a short circuit test for null and zero length:

if (s == null || s.Length == 0) ...

If you know that the referene can't be null, you can skip that check and just check the length:

if (s.Length == 0) ...

The IsNullOrEmpty method would also work for normal situations, but in the case where something went wrong and the reference is actually null, the IsNullOrEmpty method would silently accept it, while you would normally want to be made aware of the error.

Comments

0

I believe the String.IsNullOrEmpty(String s) is implemented as:

if (s == null || s.Length == 0) ...

in the API.

3 Comments

... which means as far as IL code goes, the same IL is generated. Neither is faster than the other.
I am not sure if this ok to put it here, but using Disassembler, this is what is in the API for String.IsNullOrEmptr(value) { if (value != null) { return (value.Length == 0); } return true;}
That's probably an artefact of disassembling rather than how the code actually looks.
-5

I believe the String.IsNullOrEmpty(String s) is implemented as: if (s == null || s.Length == 0) ... in the API.

That's wrong. Try it and you will get an exception as the two statement will be tried. If s is null, then s.Length will throw an execption.

1 Comment

|| short-circuits, so no, the second expression won't be evaluated if s is null. Also, not an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.