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==""所需時間最長,效率最低。