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

ASP.NET
ASP.NET错误处理:Runtime Error
如何使用ADO.NET Entity Framework从数据库中获取图片
ASP.NET教程:WaitHandle类
ASP.Net中Ado.Net Entity Framework实际项目应用释疑
ASP.NET页面中控制部分元素隐现的方法
asp.net网站开发中使用Sqlite嵌入式数据库
ASP.NET教程:调用WebService的源码
.NET中的垃圾回收
asp.net教程:编译错误同时存在于不同dll中
ASP.NET4.0新改进和新特性
ASP教程:防SQL注入
ASP.NET教程:HttpContext类Current属性
在Win2003 IIS 6.0中安装ASP.net环境
asp.net2.0中App_GlobalResources用途
利用Windows系统服务自动更新网站
无缝的缓存读取:双存储缓存策略
WebServices的性能特别慢是真的吗?
ASP.NET MVC的Web应用程序更直观
PHP和ASP.NET代码哪个运行速度更快?
ASP.NET常用代码

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-11-03   浏览: 111 ::
收藏到网摘: 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()。