和其他回答的人一样,我认为不会有性能差异,但为了确定,我运行了一个基准测试。结果并不完全符合我的预期......
这是我的基准测试的代码:
using System;
using System.Diagnostics;
static class Program
{
static void Main()
{
int count = 1;
// First run for JIT warm-up
IsNullOrEmpty(null, count);
TestEqualsEmpty(null, count);
TestLengthZero(null, count);
count = 1000000000;
Console.WriteLine("Case 1: s == \"test\"");
RunTests("test", count);
Console.WriteLine("Case 2: s == null");
RunTests(null, count);
Console.WriteLine("Case 3: s == \"\"");
RunTests("", count);
}
static void RunTests(string s, int count)
{
var ts = IsNullOrEmpty(s, count);
Console.WriteLine("\tIsNullOrEmpty: {0}", ts);
ts = TestLengthZero(s, count);
Console.WriteLine("\tTest if s.Length == 0: {0}", ts);
ts = TestEqualsEmpty(s, count);
Console.WriteLine("\tTest if s == \"\": {0}", ts);
}
static TimeSpan IsNullOrEmpty(string s, int count)
{
var sw = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
{
if (string.IsNullOrEmpty(s))
{
}
}
sw.Stop();
return sw.Elapsed;
}
static TimeSpan TestLengthZero(string s, int count)
{
var sw = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
{
if (s == null || s.Length == 0)
{
}
}
sw.Stop();
return sw.Elapsed;
}
static TimeSpan TestEqualsEmpty(string s, int count)
{
var sw = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
{
if (s == null || s == "")
{
}
}
sw.Stop();
return sw.Elapsed;
}
}
结果如下:
案例1:s ==“测试”
IsNullOrEmpty:00:00:00.6000748
测试 s.Length == 0: 00:00:00.5566793
测试 s == "": 00:00:02.2284007
案例2:s == null
IsNullOrEmpty: 00:00:00.5556170
测试 s.Length == 0: 00:00:00.5569102
测试 s == "": 00:00:00.5554338
案例 3:s == ""
IsNullOrEmpty:00:00:00.5568344
测试 s.Length == 0: 00:00:00.5556285
测试 s == "": 00:00:03.0626445
(在启用优化的情况下编译;这些是 32 位 CLR 的结果,但 64 位 CLR 的结果相似)
如您所见,如果字符串不为空,调用IsNullOrEmpty 比比较null 和"" 快得多,几乎和比较null 并测试长度是否一样快0. 如果字符串为空,则三种方法的性能相同。
所以,这样做:
if(myString != null && myString != "")
可能会比这更慢,而不是更快:
if(string.IsNullOrEmpty(myString))
你可以这样做:
if(myString != null && myString.Length > 0)
但与调用IsNullOrEmpty相比,性能提升会非常小,而且会损害可读性。
请注意,此基准测试运行了 1,000,000,000(10 亿)次迭代;这对于注意到实际差异是必要的。在现实世界的场景中,差异可能很小而无法注意到。这显然是一个微优化。