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

ASP.NET
asp.net Execl的添加,更新操作实现代码
asp.net 生成曲线图实现代码
从外部的js文件中获取ASPX页面的控件ClientID
asp.net 因为数据库正在使用的解决方法
asp.net Repeater 自递增
asp.net 实现防迅雷等下载工具盗链
ASP.NET封装的SQL数据库访问类
asp.net 通过指定IP地址得到当前的网络上的主机的域名
aspx 服务器架设问题解决
ASP.NET Session使用详解
Asp.net 5种页面转向方法
ASP.NET 用户多次登录的解决方法
ASP.NET下母版页和内容页中的事件发生顺序整理
asp.net 程序性能优化的七个方面 (c#(或vb.net)程序改进)
从客户端检测到有潜在危险的Request.Form值的asp.net代码
asp.net CommunityServer中的wwwStatus
在应用程序级别之外使用注册为allowDefinition=''MachineToApplication''的节是错误的
.net开发人员常犯的错误分析小结
ASP.net Substitution 页面缓存而部分不缓存的实现方法
asp.net 生成静态时的过滤viewstate的实现方法

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


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