str=="" str.Length==0 str==String.Empty三種方法判斷字符串爲空,哪一種更快?

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章