【问题标题】:string.IsNullOrEmpty(myString.Trim()) vs string.IsNullOrWhiteSpace(myString)string.IsNullOrEmpty(myString.Trim()) 与 string.IsNullOrWhiteSpace(myString)
【发布时间】:2012-11-26 17:24:46
【问题描述】:

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

哪个更快或更可靠,为什么会这样?

【问题讨论】:

  • 完全猜测(没有任何证据支持),我会说 IsNullOrWhiteSpace。
  • 这有关系吗? “过早的优化是万恶之源”
  • 另外,在此上下文中定义“可靠”。
  • 有趣;我在 Reflector 中查看了这个,IsNullOrWhiteSpace 并没有像人们从 MSDN 文档中所期望的那样出现在 String 命名空间中。我想知道为什么会这样。
  • @YYY 因为是后来引入的,在.NET Framework v4.0中。

标签: c# .net visual-studio-2010 visual-studio


【解决方案1】:

如果myStringnullstring.IsNullOrEmpty(myString.Trim()) 会抛出异常,而string.IsNullOrWhiteSpace(myString) 可以正常工作,因此更可靠。

至于性能,string.IsNullOrWhiteSpace 应该更快。

string.IsNullOrWhiteSpace(myString) 是检查变量是否为空或空格的首选方法。

【讨论】:

  • 那我想问string.IsNullOrEmpty(myString.Trim()) vs string.IsNullOrEmpty(myString?.Trim())
  • 现在你可以做string.IsNullOrEmpty(myString?.Trim()) 所以它不会=)
【解决方案2】:

IsNullOrWhiteSpace 是一种方便的方法,类似于 下面的代码,除了它提供了卓越的性能:

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

可靠性的唯一区别是myString.Trim() 可能会抛出NullReferenceException

从性能的角度来看,Trim 是决定因素。请注意,在Trim 的情况下,字符串是如何从每一端迭代的。正如@Lukazoid 指出的那样,在某些情况下,这可能会特别昂贵。 IsNullOrWhiteSpace 将从头开始,仅遍历字符串,直到找到非空白字符。下面是 .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);
    }

【讨论】:

【解决方案3】:

string.IsNullOrWhiteSpace(myString) 更可靠,因为当 myString 为 null 时它不会引发 NullReferenceException。 我相信 IsNullOrWhiteSpace(myString) 比 myString.Trim() 快,想想一个字符串,两端包含 1 个空格,中间包含 300 万个其他字符。在检查之前,这三百万个字符必须被复制到一个新字符串中。 IsNullOrWhiteSpace 必须比较两个字符。

【讨论】:

    【解决方案4】:

    String.IsNullOrWhiteSpace() 将更加可靠和快速。

    更可靠,因为它可以正确处理 null。而且速度更快,因为它不需要创建新字符串。

    【讨论】:

    • Here 它说IsNullOrWhiteSpace 更慢。
    • IsNullOrWhiteSpace() IsNullOrEmpty() 慢。但是,最初的问题是将其与string.IsNullOrEmpty(myString.Trim()) 进行比较。调用Trim() 必须在测试之前创建一个新字符串并从原始字符串中复制字符。总之,我很确定IsNullOrWhiteSpace() 会更快。
    【解决方案5】:

    如果你真的想在优化方面走这么远,string.IsNullOrWhiteSpace(myString) 会有更好的性能,因为它能够立即返回结果。

    取以下字符串:

    " B C    " (4 trailing spaces)
    

    string.IsNullOrEmpty(myString.Trim()):

    1. 修剪字符串,迭代超过 5 个字符(1 个前导和 4 个尾随空格),生成“B C”
    2. IsNullOrEmpty 迭代 1 个字符并返回 false。

    总共检查了 6 个字符。

    string.IsNullOrWhitespace(myString):

    1. 遍历 2 个字符,第二个字符返回 false

    总共检查了 2 个字符。

    尾随空格的数量越多,string.IsNullOrWhitespace(myString) 提供的优势就越大。

    正如其他答案和 cmets 中所述,来自Trim() 的附加字符串的实例化会增加更多开销。

    【讨论】:

    • Trim() 从头到尾迭代。真正的区别在于它必须实例化一个新字符串
    • @Tar 我没想到,谢谢你告诉我,我真的应该用反射器。我将更新我的答案以纳入这些知识
    【解决方案6】:

    这取决于您的应用程序,但您必须小心转义字符。 这里我们考虑String.IsNullOrEmpty

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

    现在String.IsNullOrWhiteSpace:

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

    【讨论】:

    • 如果您像 OP 一样将 Trim 应用于传递给 string.IsNullOrEmpty 的值会怎样?
    • @GuruStron 是的,通过对 String.IsNullOrEmpty 应用 Trim,转义字符将为空,因此两种方法返回相同的结果。
    猜你喜欢
    • 2013-11-11
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    相关资源
    最近更新 更多