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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With