Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.IsNullOrEmpty(myString.Trim()) vs string.IsNullOrWhiteSpace(myString)

string.IsNullOrEmpty(myString.Trim()) vs string.IsNullOrWhiteSpace(myString)

Which one is faster or more reliable and why is that?

like image 453
NET3 Avatar asked Dec 01 '22 20:12

NET3


2 Answers

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.

like image 190
Zbigniew Avatar answered Dec 04 '22 10:12

Zbigniew


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);
    }
like image 22
Ryan Gates Avatar answered Dec 04 '22 11:12

Ryan Gates