您好,欢迎访问一九零五行业门户网

解决遍历时Array.indexOf产生的性能问题_javascript技巧

复制代码 代码如下:
ext.applyif(array.prototype, {
/**
* checks whether or not the specified object exists in the array.
* @param {object} o the object to check for
* @param {number} from (optional) the index at which to begin the search
* @return {number} the index of o in the array (or -1 if it is not found)
*/
indexof : function(o, from){
var len = this.length;
from = from || 0;
from += (from for (; from if(this[from] === o){
return from;
}
});
return -1;
}
从源码可以看出,查找是简单的线性查找。
由于线性查找效率是 o(n) ,所以,在数据量稍大的时候,需要寻找替代 array 的办法。有很多文章说过关于 array 的这个问题,包括《权威指南》,办法是模拟一个 hash 表。
下面是有问题的代码
复制代码 代码如下:
var hostsip = [];
ext.each(_this.hosts,function(item){
hostsip.push(item.ip);
});
ext.each(txthostsip,function(ip){
if(hostsip.indexof(ip)===-1){//问题代码
var host = {
isappend : true,//新增的主机
isagentok : false,
ip : ip
};
_this.hosts.push(
ext.apply(host,_this.mapping_fields)
);
isappend = true;
}else{
errors.push('ip['+ip+']已存在');
}
});
当hostsip长度超过2000个时,ie8-浏览器会出现如下提示
按照《权威指南》中给出的提示,我对代码做了如下修改后,问题解决。
复制代码 代码如下:
var hostsip = {};
ext.each(_this.hosts,function(item){
hostsip[item.ip]=item.ip;
});
ext.each(txthostsip,function(ip){
if(!hostsip.hasownproperty(ip)){
var host = {
isappend : true,//新增的主机
isagentok : false,
ip : ip
};
_this.hosts.push(
ext.apply(host,_this.mapping_fields)
);
isappend = true;
}else{
errors.push('ip['+ip+']已存在');
}
});
其它类似信息

推荐信息