要比较两个字符串是否相等,有两种方法:
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()。 
|