检查字符串是否为空的最佳方法是什么?

now*_*ed. 8 c# .net-4.0 visual-studio-2010

要检查字符串是否为空,我使用

var test = string.Empty; 
if (test.Length == 0) Console.WriteLine("String is empty!");
if (!(test.Any())) Console.WriteLine("String is empty!");
if (test.Count() == 0) Console.WriteLine("String is empty!");
if (String.IsNullOrWhiteSpace(test)) Console.WriteLine("String is empty!");
Run Code Online (Sandbox Code Playgroud)
  1. 以上所有语句都产生相同的输出.我应该使用的最佳方法是什么?

    var s = Convert.ToString(test);    
    s = test.ToString(CultureInfo.InvariantCulture);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 同样,两个陈述都做同样的事情.什么是最好的使用方法?

我试过调试以及如何对C#语句的性能进行基准测试?

Pet*_*ter 10

首先,4个statemens没有在所有输入上给出相同的输出.尝试null,前3个将抛出异常.并尝试whithspaces,最后一个会给你一个失败的结果.所以你真的要考虑你想要的东西.最好的方法通常是:

string.IsNullOrEmpty
string.IsNullOrWhiteSpace
Run Code Online (Sandbox Code Playgroud)

只有你这样做几百万次,你才应该看看如何进一步优化你的代码.

这里有一些测试结果,但这在任何.net版本上都有所不同:

1亿次迭代的测试结果:

Equality operator ==:   796 ms 
string.Equals:          811 ms 
string.IsNullOrEmpty:   312 ms 
Length:                 140 ms  [fastest]
Instance Equals:       1077 ms 
Run Code Online (Sandbox Code Playgroud)

资源