也谈String.IsNullOrEmpty
今天在浏览DevTopics的博客时,发现一篇介绍String的随笔,介绍的是判断一个String变量是否为空时,String的一个方法和一个属性之间的比较,给一个 string变量 's', 下面那个表达式更快?
这里有一个简单的例子来比较2种方式:
1. String.IsNullOrEmpty( s )
2. s == null || s.Length == 0
如果你猜第二个,那么你是对的. 它将比String.IsNullOrEmpty方法快15%,但这种也是以百万分之一秒来衡量的!2. s == null || s.Length == 0
这里有一个简单的例子来比较2种方式:
using System;
namespace StringNullEmpty
{
class Program
{
static void Main( string[] args )
{
long loop = 100000000;
string s = null;
long option = 0;
long empties1 = 0;
long empties2 = 0;
DateTime time1 = DateTime.Now;
for (long i = 0; i < loop; i++)
{
option = i % 4;
switch (option)
{
case 0:
s = null;
break;
case 1:
s = String.Empty;
break;
case 2:
s = "H";
break;
case 3:
s = "HI";
break;
}
if (String.IsNullOrEmpty( s ))
empties1++;
}
DateTime time2 = DateTime.Now;
for (long i = 0; i < loop; i++)
{
option = i % 4;
switch (option)
{
case 0:
s = null;
break;
case 1:
s = String.Empty;
break;
case 2:
s = "H";
break;
case 3:
s = "HI";
break;
}
if (s == null || s.Length == 0)
empties2++;
}
DateTime time3 = DateTime.Now;
TimeSpan span1 = time2.Subtract( time1 );
TimeSpan span2 = time3.Subtract( time2 );
Console.WriteLine( "(String.IsNullOrEmpty( s )): Time={0} Empties={1}",
span1, empties1 );
Console.WriteLine( "(s == null || s.Length == 0): Time={0} Empties={1}",
span2, empties2 );
Console.ReadLine();
}
}
}
下面是结果:
(String.IsNullOrEmpty( s )): Time=00:00:06.8437500 Empties=50000000
(s == null || s.Length == 0): Time=00:00:05.9218750 Empties=50000000
namespace StringNullEmpty
{
class Program
{
static void Main( string[] args )
{
long loop = 100000000;
string s = null;
long option = 0;
long empties1 = 0;
long empties2 = 0;
DateTime time1 = DateTime.Now;
for (long i = 0; i < loop; i++)
{
option = i % 4;
switch (option)
{
case 0:
s = null;
break;
case 1:
s = String.Empty;
break;
case 2:
s = "H";
break;
case 3:
s = "HI";
break;
}
if (String.IsNullOrEmpty( s ))
empties1++;
}
DateTime time2 = DateTime.Now;
for (long i = 0; i < loop; i++)
{
option = i % 4;
switch (option)
{
case 0:
s = null;
break;
case 1:
s = String.Empty;
break;
case 2:
s = "H";
break;
case 3:
s = "HI";
break;
}
if (s == null || s.Length == 0)
empties2++;
}
DateTime time3 = DateTime.Now;
TimeSpan span1 = time2.Subtract( time1 );
TimeSpan span2 = time3.Subtract( time2 );
Console.WriteLine( "(String.IsNullOrEmpty( s )): Time={0} Empties={1}",
span1, empties1 );
Console.WriteLine( "(s == null || s.Length == 0): Time={0} Empties={1}",
span2, empties2 );
Console.ReadLine();
}
}
}
下面是结果:
(String.IsNullOrEmpty( s )): Time=00:00:06.8437500 Empties=50000000
(s == null || s.Length == 0): Time=00:00:05.9218750 Empties=50000000