轉載:http://www.cnblogs.com/bit-sand/archive/2007/07/27/834148.html
今天突然有興做了兩下有關字串為空白的效能測試,與大家分享!結果如下:
兩種賦值方式的比較:
string str="";
string str=string.Empty;
理論上講:
string.Empty是一個Static的屬性,使用時不分配儲存空間,而在用""時,系統會分配一個長度為空白的儲存空間。不過編譯系統應該會最佳化,也就是說,比如你程式中有10個地方用到了"",但好的編譯系統應該引用的是同一個對象。所以用""也就是浪費一個對象空間而已。
實戰:
測試程式如下:
namespace testEmpty
{
class Program
{
static void Main(string[] args)
{
Test test = new Test();
test.testEmpty();
test.testEqualEmpty();
Console.Read();
}
}
class Test
{
public void testEmpty()
{
string str;
for (int i = 0; i < 10000; i++)
{
str = "";
}
}
public void testEqualEmpty()
{
string str;
for (int i = 0; i < 10000; i++)
{
str = string.Empty;
}
}
}
}
測試過程是分別將指派陳述式str=""和str=string.Empty用兩個函數執行10000次,所用時間如下所示:
所以說:單獨執行testEmpty()執行10000次用了0.262669毫秒,單獨執行testEqualEmpty()執行0.026849毫秒。前者是後者的10倍.
下面介紹的是幾種判斷語句的比較:
我想到的所有的判斷Null 字元串的語句就這幾種了,大家還有其它方法的歡迎討論!
str == ""
str.Equals("")
str==string.Empty
str.Equals(string.Empty)
str .Length==0
測試程式如下:
using System;
using System.Collections.Generic;
using System.Text;
namespace testEmpty
{
class Program
{
static void Main(string[] args)
{
Test test = new Test();
test.test1();
test.test2();
test.test3();
test.test4();
test.test5();
Console.Read();
}
}
class Test
{
string str = string.Empty;
public void test1()
{
for (int i = 0; i < 10000; i++)
{
if (str == "")
{
Console.WriteLine("1 This string is emput");
}
}
}
public void test2()
{
for (int i = 0; i < 10000; i++)
{
if (str.Equals(""))
{
Console.WriteLine("2 This string is emput");
}
}
}
public void test3()
{
for (int i = 0; i < 10000; i++)
{
if (str==string.Empty)
{
Console.WriteLine("3 This string is emput");
}
}
}
public void test4()
{
for (int i = 0; i < 10000; i++)
{
if (str.Equals(string.Empty))
{
Console.WriteLine("4 This string is emput");
}
}
}
public void test5()
{
for (int i = 0; i < 10000; i++)
{
if (str .Length==0)
{
Console.WriteLine("5 This string is emput");
}
}
}
}
}
在這個測試程式中,用了5個分別含有這5種判斷語句的方法,目的就是為了測試每個方法耗費的時間。
在這裡說明一下,筆者在這個程式中起的名字不可取,程式員不應該這樣為方法起名字的,見笑了!
測試結果如下:
呵呵,可以從這個方法耗費時間詳細說明表中看出,這些方法耗費時間都比較,這主要是因為裡面的Console.WriteLine()語句影響的。但是每個方法中都有這一語句,所以說它並不影響我們的比較結果!
得出的結論:在字串為空白時,這五種判斷語句的耗費時間由短到長
str .Length==0
str.Equals("")
str==string.Empty
str.Equals(string.Empty)
str == ""
你平時有的哪種比較語句呢?呵呵……
需要說明的是:這隻是在字串為空白時結果是這樣的,那麼字串不為空白時呢,結果又是怎樣的呢?