简体   繁体   中英

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?

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);
    }

string.IsNullOrWhiteSpace(myString) is more reliable because it will not raise a NullReferenceException when myString is null. I believe that IsNullOrWhiteSpace(myString) is faster than myString.Trim(), think of a string containing 1 space in both ends and three million other chars in the middle. These three million chars would have to be copied to a new string before checking. IsNullOrWhiteSpace would have to compare two chars.

String.IsNullOrWhiteSpace() will be both more reliable and faster.

More reliable because it correctly handles null. And faster because it doesn't need to create a new string.

If you really want to go this far in terms of optimization, string.IsNullOrWhiteSpace(myString) will have better performance as it is able to return a result immediately.

Take the following string:

" B C    " (4 trailing spaces)

With string.IsNullOrEmpty(myString.Trim()) :

  1. Trim the string, iterating over 5 characters (1 preceeding and 4 trailing spaces), resulting in "BC"
  2. IsNullOrEmpty iterates 1 character and returns false.

Total of 6 characters checked.

With string.IsNullOrWhitespace(myString) :

  1. Iterate over 2 characters, returns false on the second character

Total of 2 characters checked.

The larger the number of trailing spaces, the bigger the benefits string.IsNullOrWhitespace(myString) will provide over the alternative.

As states in other answers and comments, the instantiation of the additional string result from Trim() adds more overhead.

It depends on your application but you must be careful of escaped characters. Here we considering String.IsNullOrEmpty :

String.IsNullOrEmpty(""); //True
String.IsNullOrEmpty(null); //True
String.IsNullOrEmpty("   "); //False
String.IsNullOrEmpty("\n"); //False
String.IsNullOrEmpty("\t"); //False
String.IsNullOrEmpty("hello"); //False

and now String.IsNullOrWhiteSpace :

String.IsNullOrWhiteSpace("");//True
String.IsNullOrWhiteSpace(null);//True
String.IsNullOrWhiteSpace("   ");//True
String.IsNullOrWhiteSpace("\n");//True
String.IsNullOrWhiteSpace("\t");//True
String.IsNullOrWhiteSpace("hello");//False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM