简体   繁体   English

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

[英]string.IsNullOrEmpty(myString.Trim()) vs string.IsNullOrWhiteSpace(myString)

string.IsNullOrEmpty(myString.Trim()) vs string.IsNullOrWhiteSpace(myString) string.IsNullOrEmpty(myString.Trim())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. 如果myStringnullstring.IsNullOrEmpty(myString.Trim())将抛出异常,而string.IsNullOrWhiteSpace(myString)将正常工作,因此它更可靠。

As for the performance, string.IsNullOrWhiteSpace should be faster. 至于性能, string.IsNullOrWhiteSpace应该更快。

string.IsNullOrWhiteSpace(myString) is prefered way of checking if variable is empty or whitespace. string.IsNullOrWhiteSpace(myString)是检查变量是空还是空格的首选方法。

IsNullOrWhiteSpace is a convenience method that is similar to the following code, except that it offers superior performance: IsNullOrWhiteSpace是一种方便的方法,类似于以下代码,只是它提供了卓越的性能:

return String.IsNullOrEmpty(value) || value.Trim().Length == 0;

The only difference in reliability is that myString.Trim() may throw a NullReferenceException . 可靠性的唯一区别是myString.Trim()可能抛出NullReferenceException

From a performance standpoint, Trim is the deciding factor. 从性能角度来看, Trim是决定性因素。 Notice how in the case of Trim the string is iterated through from each end. 注意在Trim的情况下,如何从每一端迭代字符串。 This can be especially costly in some cases, as @Lukazoid noted. 在某些情况下,这可能特别昂贵,正如@Lukazoid所指出的那样。 IsNullOrWhiteSpace will start from the beginning and only iterate through the string until a non-whitespace character is found. IsNullOrWhiteSpace将从头开始,只遍历字符串,直到找到非空白字符。 Below is the .NET source. 下面是.NET源代码。

    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. string.IsNullOrWhiteSpace(myString)更可靠,因为当myString为null时,它不会引发NullReferenceException。 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. 我相信IsNullOrWhiteSpace(myString)比myString.Trim()快,想到一个字符串,两端包含1个空格,中间包含300万个其他字符。 These three million chars would have to be copied to a new string before checking. 在检查之前,必须将这三百万个字符复制到一个新字符串。 IsNullOrWhiteSpace would have to compare two chars. IsNullOrWhiteSpace必须比较两个字符。

String.IsNullOrWhiteSpace() will be both more reliable and faster. String.IsNullOrWhiteSpace()将更可靠,更快捷。

More reliable because it correctly handles null. 更可靠,因为它正确处理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. 如果你真的想在优化方面走得那么远, string.IsNullOrWhiteSpace(myString)会有更好的性能,因为它能够立即返回结果。

Take the following string: 请使用以下字符串:

" B C    " (4 trailing spaces)

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

  1. Trim the string, iterating over 5 characters (1 preceeding and 4 trailing spaces), resulting in "BC" 修剪字符串,迭代超过5个字符(前1个和4个尾随空格),产生“BC”
  2. IsNullOrEmpty iterates 1 character and returns false. IsNullOrEmpty迭代1个字符并返回false。

Total of 6 characters checked. 共检查了6个字符。

With string.IsNullOrWhitespace(myString) : 使用string.IsNullOrWhitespace(myString)

  1. Iterate over 2 characters, returns false on the second character 迭代超过2个字符,在第二个字符上返回false

Total of 2 characters checked. 共检查了2个字符。

The larger the number of trailing spaces, the bigger the benefits string.IsNullOrWhitespace(myString) will provide over the alternative. 尾随空格的数量越大, string.IsNullOrWhitespace(myString)益处越大string.IsNullOrWhitespace(myString)将提供替代方案。

As states in other answers and comments, the instantiation of the additional string result from Trim() adds more overhead. 作为其他答案和注释中的状态, Trim()的附加字符串结果的实例化会增加更多开销。

It depends on your application but you must be careful of escaped characters.这取决于您的应用程序,但您必须小心转义字符。 Here we considering String.IsNullOrEmpty :这里我们考虑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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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