string.IsNullOrEmpty(myString.Trim())
vs string.IsNullOrWhiteSpace(myString)
Which one is faster or more reliable and why is that?
string.IsNullOrEmpty(myString.Trim())
will throw exception if myString
is null
, whereas string.IsNullOrWhiteSpace(myString)
will work just fine, so it's more reliable.
As for the performance, string.IsNullOrWhiteSpace
should be faster.
string.IsNullOrWhiteSpace(myString)
is prefered way of checking if variable is empty or whitespace.
IsNullOrWhiteSpace is a convenience method that is similar to the following code, except that it offers superior performance:
return String.IsNullOrEmpty(value) || value.Trim().Length == 0;
The only difference in reliability is that myString.Trim()
may throw a NullReferenceException.
From a performance standpoint, Trim is the deciding factor. Notice how in the case of Trim the string is iterated through from each end. This can be especially costly in some cases, as @Lukazoid noted. IsNullOrWhiteSpace will start from the beginning and only iterate through the string until a non-whitespace character is found. Below is the .NET source.
public static bool IsNullOrEmpty(String value) {
return (value == null || value.Length == 0);
}
[Pure]
public static bool IsNullOrWhiteSpace(String value) {
if (value == null) return true;
for(int i = 0; i < value.Length; i++) {
if(!Char.IsWhiteSpace(value[i])) return false;
}
return true;
}
// Trims the whitespace from both ends of the string. Whitespace is defined by
// Char.IsWhiteSpace.
//
[Pure]
public String Trim() {
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return TrimHelper(TrimBoth);
}
[System.Security.SecuritySafeCritical] // auto-generated
private String TrimHelper(int trimType) {
//end will point to the first non-trimmed character on the right
//start will point to the first non-trimmed character on the Left
int end = this.Length-1;
int start=0;
//Trim specified characters.
if (trimType !=TrimTail) {
for (start=0; start < this.Length; start++) {
if (!Char.IsWhiteSpace(this[start])) break;
}
}
if (trimType !=TrimHead) {
for (end= Length -1; end >= start; end--) {
if (!Char.IsWhiteSpace(this[end])) break;
}
}
return CreateTrimmedString(start, end);
}
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