Tuesday, February 12, 2008

Check a String for Null or Empty

Yes, the method that .NET Framework 2.0 provides is the fastest.

You used to do it this way (I hope :):
if (s == null || s.Length == 0)

Checking the length is faster that comparing to "" or string.Empty, because the length is simply stored together with the string's content on the heap (see: Strings in .NET and C#, 'Memory usage').

.NET Framework 2.0 put the above check into a single static method of string:
if (string.IsNullOrEmpty(s))

For all the doubting Thomases ;) - this guy actually tested it:
String.Empty, null, Length, or String.IsEmptyOrNull

No comments: