“String.Equals(string)”和“==”那个快?

王朝c#·作者佚名  2006-12-17
宽屏版  字体: |||超大  

要比较两个字符串是否相等,有两种方法:

string toBeTested = "67412";

bool result;

result = toBeTested.Equals("67413");

result = toBeTested == "67413";

哪一种方法好呢?

测试程序:

int times = 100000000;

int start, end;

int i;

bool result;

string toBeTested = "67412";

start = System.Environment.TickCount;

for(i=0; i<times; i++)

{

result = toBeTested.Equals("67412");

}

end = System.Environment.TickCount;

Console.WriteLine("Equals True Time: " + (end-start)/1000.0 + " Seconds");

start = System.Environment.TickCount;

for(i=0; i<times; i++)

{

result = toBeTested == "67412";

}

end = System.Environment.TickCount;

Console.WriteLine("== True Time: " + (end-start)/1000.0 + " Seconds");

start = System.Environment.TickCount;

for(i=0; i<times; i++)

{

result = toBeTested.Equals("67413");

}

end = System.Environment.TickCount;

Console.WriteLine("Equals False Time: " + (end-start)/1000.0 + " Seconds");

start = System.Environment.TickCount;

for(i=0; i<times; i++)

{

result = toBeTested == "67413";

}

end = System.Environment.TickCount;

Console.WriteLine("== False Time: " + (end-start)/1000.0 + " Seconds");

结果:

Equals True Time: 3.234 Seconds

== True Time: 0.562 Seconds

Equals False Time: 3.391 Seconds

== False Time: 3.891 Seconds

可见当结果为true时,==比Equals()快很多;当结果为false时,Equals()略快于==。

结论:如果要比较的字符串相同的多,就用==;要比较的字符串中不同的多,就用Equals()。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有