当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > “String.Equals(string)”和“==”那个快?

ASP.NET
如何在ASP.NET中使用SmtpMail发送邮件
在VB.NET中利用Split和Replace函数计算字数
Attribute应用:简化ANF自定义控件初始化过程
ASP.NET 2.0移动开发入门之使用样式
ASP.NET 2.0中使用OWC生成图表
ASP.NET 2.0中控件的简单异步回调
一个无法捕获ADO.NET Dataset的内存错误
深入解读ADO.NET2.0的十大最新特性
.Net平台下的分布式缓存设计
ASP.NET全局异常处理浅析
ASP.NET 2.0中文验证码的实现
浅析.NET平台编程语言的未来走向
.net 框架程序设计收藏
使用ASP.NET MVC Futures 中的异步Action
详解.NET中的XmlReader与XmlWriter
关于.NET中的Server push技术
asp.net页面执行机制
对比JSP和ASP.NET的存储过程
.NET 4.0不会包含System.Shell.CommandLine
ASP.NET十个有效性能优化的方法

ASP.NET 中的 “String.Equals(string)”和“==”那个快?


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-11-03   浏览: 180 ::
收藏到网摘: n/a


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

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 {
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 {
result = toBeTested == "67412";
}
end = System.Environment.TickCount;
Console.WriteLine("== True Time: " + (end-start)/1000.0 + " Seconds");
start = System.Environment.TickCount;
for(i=0; 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 {
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()。