Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Empty, null, Length, or String.IsEmptyOrNull?

Tags:

string

c#

Which way is really the fastest way to check for an empty string and there is any specific case where need to any specific.

1. String.IsNullOrEmpty()

2. str == null

3. str == null || str == String.Empty

4. str == null || str == ""

5. str == null || str.length == 0
like image 561
Pankaj Agarwal Avatar asked Jan 05 '12 12:01

Pankaj Agarwal


2 Answers

Use option 1.

If you specifically want to check for null or empty strings, then there's no reason to use anything other than string.IsNullOrEmpty. It's the canonical way of doing so in .NET, and any differences in performance will be almost certainly be negligible.

This is a textbook example of premature optimization; by all means, write efficient code, but don't waste development time over it for no justifiable gain in performance. Remember that your time as a developer is generally far more valuable than the CPU's time.

Quoth Donald Knuth:

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

If this level of micro-optimisation is genuinely necessary for your application, then you probably shouldn't be using .NET.

like image 171
Will Vousden Avatar answered Sep 19 '22 00:09

Will Vousden


Do you care about whitespace as well?

If whitespace is valid, use String.IsNullOrEmpty, otherwise use String.IsNullOrWhiteSpace (in .Net 4.0 or higher). The latter is equivalent to, but more performant than, String.IsNullOrEmpty(value) || value.Trim().Length == 0;

see http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx

like image 45
ZombieSheep Avatar answered Sep 19 '22 00:09

ZombieSheep