解决遍历时,Array.indexOf产生的性能问题

javascript中数组是没有indexOf方法,extjs中给数据添加了该方法

 1 Ext.applyIf(Array.prototype, {
 2     
 3 /**
 4      * Checks whether or not the specified object exists in the array.
 5      * @param {Object} o The object to check for
 6      * @param {Number} from (Optional) The index at which to begin the search
 7      * @return {Number} The index of o in the array (or -1 if it is not found)
 8      */
 9     indexOf : function(o, from){
10         var len = this.length;
11         from = from || 0;
12         from += (from < 0) ? len : 0;
13         for (; from < len; ++from){
14             if(this[from] === o){
15                 return from;
16             }
17         });
18         return -1;
19     }

从源码可以看出,查找是简单的线性查找。

由于线性查找效率是 O(n) ,所以,在数据量稍大的时候,需要寻找替代 Array 的办法。有很多文章说过关于 Array 的这个问题,包括《权威指南》,办法是模拟一个 Hash 表。

下面是有问题的代码

 1 var hostsIP = [];
 2 Ext.each(_this.hosts,function(item){
 3     hostsIP.push(item.ip);
 4 });
 5 
 6 Ext.each(txtHostsIP,function(ip){
 7     if(hostsIP.indexOf(ip)===-1){//问题代码
 8         var host = {
 9             isAppend : true,//新增的主机
10             isAgentOk : false,
11             ip : ip
12         };
13         _this.hosts.push(
14             Ext.apply(host,_this.MAPPING_FIELDS)
15         );
16         isAppend = true;
17     }else{
18         errors.push('IP['+ip+']已存在');
19     }
20 }); 

当hostsIP长度超过2000个时,IE8-浏览器会出现如下提示

按照《权威指南》中给出的提示,我对代码做了如下修改后,问题解决。

 

 1 var hostsIP = {};
 2 Ext.each(_this.hosts,function(item){
 3     hostsIP[item.ip]=item.ip;
 4 });
 5 
 6 Ext.each(txtHostsIP,function(ip){
 7     if(!hostsIP.hasOwnProperty(ip)){
 8         var host = {
 9             isAppend : true,//新增的主机
10             isAgentOk : false,
11             ip : ip
12         };
13         _this.hosts.push(
14             Ext.apply(host,_this.MAPPING_FIELDS)
15         );
16         isAppend = true;
17     }else{
18         errors.push('IP['+ip+']已存在');
19     }
20 }); 

 

转载于:https://www.cnblogs.com/kenn/archive/2012/06/29/2570122.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值