要检查字符串是否为空,我使用
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!");
以上所有语句都会产生相同的输出。我应该使用的最佳方法是什么?
var s = Convert.ToString(test);
s = test.ToString(CultureInfo.InvariantCulture);
同样,两个陈述都是一样的。什么是最好的使用方法?
我尝试过调试以及如何对C#语句的性能进行基准测试?
答案 0 :(得分:10)
首先,4个statemens没有在所有输入上给出相同的输出。尝试null,前3个将抛出异常。并尝试whithspaces,最后一个会给你一个失败的结果。所以你真的要考虑你想要的东西。最好的方法通常是:
string.IsNullOrEmpty
string.IsNullOrWhiteSpace
只有当你这样做几百万次时,你才应该看看如何进一步优化你的代码。
这里有一些测试结果,但这在任何.net版本上都有所不同:
1亿次迭代的测试结果:
Equality operator ==: 796 ms
string.Equals: 811 ms
string.IsNullOrEmpty: 312 ms
Length: 140 ms [fastest]
Instance Equals: 1077 ms
答案 1 :(得分:3)
我会选择String.IsNullOrWhiteSpace
或String.IsNullOrEmpty
。
Length
Count
为Any
,则{p> test
,null
和object null reference
可能会失败
除非您确定您的字符串不为null,否则您必须在测试长度或计数或调用变量上的任何方法之前检查字符串是否为空。
在这些情况下,.Length
与String.IsNullOrWhiteSpace
string test = " ";
test.Length == 0; //false
String.IsNullOrWhiteSpace(test); //true
答案 2 :(得分:1)
据我所知:
.Any()
:旨在检查数组中是否存在任何对象。由于string是一个char数组,因此可行。并且是Linq的一部分
.Length
:旨在为您提供char数组的长度。
所以,是的是相同的行为,但意图略有不同。
顺便说一句,你应该使用String.IsNullOrWhitespace
来检查字符串为空。至少这是我的偏好,所以如果你有一个包含许多空白字符的字符串,你不必先修剪。
答案 3 :(得分:1)
对于一个变量,结果是:
String.IsNullOrEmpty(test)
< String.IsNullOrWhiteSpace(test)
<< test.Length==0
<<< !(test.Any())
{≡{1}} test.Count() == 0
< test.ToString(CultureInfo.InvariantCulture)
(订购10次)我使用以下代码片段来测试上述内容。
Convert.ToString(test)
Infact static void Main(string[] args)
{
var test = string.Empty;
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
if (test.Length == 0)
{
sw.Stop();
Console.WriteLine("String is empty! " + sw.ElapsedTicks);
}
sw.Restart();
if (!(test.Any()))
{
sw.Stop();
Console.WriteLine("String is empty! " + sw.ElapsedTicks);
}
sw.Restart();
if (String.IsNullOrWhiteSpace(test))
{
sw.Stop();
Console.WriteLine("String is empty! " + sw.ElapsedTicks);
}
sw.Restart();
if (String.IsNullOrEmpty(test))
{
sw.Stop();
Console.WriteLine("String is empty! " + sw.ElapsedTicks);
}
sw.Restart();
if (test.Count() == 0)
{
sw.Stop();
Console.WriteLine("String is empty! " + sw.ElapsedTicks);
}
sw.Restart();
var s = Convert.ToString(test);
sw.Stop();
Console.WriteLine("String is empty! " + sw.ElapsedTicks);
sw.Restart();
s = test.ToString(CultureInfo.InvariantCulture);
sw.Stop();
Console.WriteLine("String is empty! " + sw.ElapsedTicks);
Console.ReadKey();
}
是最好的,正如上面评论中有人所指出的那样...... :)