Which one is better among the three?
string myString = ""; String.IsNullOrEmpty(myString); vs string myString = ""; if(myString.Length > 0 || myString != null) vs string myString = ""; if (m.Length > 0 | m != null)
Faster clearer, but is there a difference in performance between the two? What if the string is never empty, for example, if it is taken from a text field that may be empty but not empty?
Well, the version in question:
if(myString.Length > 0 || myString != null)
, null ( ) - null, .Length. string.IsNullOrEmpty. , , ( null).
null
.Length
string.IsNullOrEmpty
static bool HasValue(this string s) { return !string.IsNullOrEmpty(s); }
string.IsNullOrEmpty(str). . .
string.IsNullOrEmpty(str)
"", string.Empty, .
string.Empty
IsNullOrEmpty.
, .
- . , : " , myString.trim(). Length!= 0 " .
: - , , .
, IsNullOrEmpty() JIT (. ).
, - , .NET, .NET 4:
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] public static bool IsNullOrEmpty(string value) { if (value != null) { return (value.Length == 0); } return true; }
, NGen ( native).
String.IsNullOrEmpty - , , ( , , , ...;).
String.IsNullOrEmpty
IsNullOrEmpty:
IsNullOrEmpty
if (String.IsNullOrEmpty(s)) ...
:
if (s == null || s.Length == 0) ...
, , :
if (s.Length == 0) ...
IsNullOrEmpty , , - , , IsNullOrEmpty , , , .
, String.IsNullOrEmpty(String s) :
if (s == null || s.Length == 0)...
API.
I believe the String.IsNullOrEmpty(String s) is implemented as: if (s == null || s.Length == 0) ... in the API.
. , , . s NULL, s.Length .