str==""
str.Length==0
str==String.Empty
这是三种用来判断字符串是否为空的方法,那么这三种方法哪一种执行起来更快呢?
为了得出结果,我在vs.net 2005中写了下面这一小段程序来进行判断:
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Test
{
public static void Main()
{
string str = "ljdfskldfsklj";
//System.Diagnostics.Stopwatch提供了一组方法和属性,可以准确地测量运行时间
Stopwatch sw;
sw=Stopwatch.StartNew();
if (str == "") ;
Console.WriteLine("str==/"/" 花费/t{0}", sw.Elapsed);
sw = Stopwatch.StartNew();
if (str.Length == 0) ;
Console.WriteLine("str.Length==0 花费/t{0}", sw.Elapsed);
sw = Stopwatch.StartNew();
if (str == String.Empty) ;
Console.WriteLine("str==String.Empty 花费/t{0}", sw.Elapsed);
}
}
}
运行结果如下(结果可能会因不同的软硬件环境而不同,但最终时间顺序是一样的):
str=="" 花费 00:00:00.0000044
str.Length==0 花费 00:00:00.0000027
str==String.Empty 花费 00:00:00.0000036
由结果可以看出str.Length==0所需时间最短,str==String.Empty次之,str==""所需时间最长,效率最低。