欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

解決遍歷時(shí)Array.indexOf產(chǎn)生的性能問(wèn)題

 更新時(shí)間:2012年07月03日 11:47:36   作者:  
javascript中數(shù)組是沒(méi)有indexOf方法,extjs中給數(shù)據(jù)添加了該方法
復(fù)制代碼 代碼如下:

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 < 0) ? len : 0;
for (; from < len; ++from){
if(this[from] === o){
return from;
}
});
return -1;
}

從源碼可以看出,查找是簡(jiǎn)單的線性查找。
由于線性查找效率是 O(n) ,所以,在數(shù)據(jù)量稍大的時(shí)候,需要尋找替代 Array 的辦法。有很多文章說(shuō)過(guò)關(guān)于 Array 的這個(gè)問(wèn)題,包括《權(quán)威指南》,辦法是模擬一個(gè) Hash 表。
下面是有問(wèn)題的代碼
復(fù)制代碼 代碼如下:

var hostsIP = [];
Ext.each(_this.hosts,function(item){
hostsIP.push(item.ip);
});
Ext.each(txtHostsIP,function(ip){
if(hostsIP.indexOf(ip)===-1){//問(wèn)題代碼
var host = {
isAppend : true,//新增的主機(jī)
isAgentOk : false,
ip : ip
};
_this.hosts.push(
Ext.apply(host,_this.MAPPING_FIELDS)
);
isAppend = true;
}else{
errors.push('IP['+ip+']已存在');
}
});

當(dāng)hostsIP長(zhǎng)度超過(guò)2000個(gè)時(shí),IE8-瀏覽器會(huì)出現(xiàn)如下提示

按照《權(quán)威指南》中給出的提示,我對(duì)代碼做了如下修改后,問(wèn)題解決。
復(fù)制代碼 代碼如下:

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,//新增的主機(jī)
isAgentOk : false,
ip : ip
};
_this.hosts.push(
Ext.apply(host,_this.MAPPING_FIELDS)
);
isAppend = true;
}else{
errors.push('IP['+ip+']已存在');
}
});

相關(guān)文章

最新評(píng)論