解決遍歷時Array.indexOf產(chǎn)生的性能問題
更新時間:2012年07月03日 11:47:36 作者:
javascript中數(shù)組是沒有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;
}
從源碼可以看出,查找是簡單的線性查找。
由于線性查找效率是 O(n) ,所以,在數(shù)據(jù)量稍大的時候,需要尋找替代 Array 的辦法。有很多文章說過關(guān)于 Array 的這個問題,包括《權(quán)威指南》,辦法是模擬一個 Hash 表。
下面是有問題的代碼
復(fù)制代碼 代碼如下:
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-瀏覽器會出現(xià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,//新增的主機
isAgentOk : false,
ip : ip
};
_this.hosts.push(
Ext.apply(host,_this.MAPPING_FIELDS)
);
isAppend = true;
}else{
errors.push('IP['+ip+']已存在');
}
});
您可能感興趣的文章:
- 詳談js遍歷集合(Array,Map,Set)
- Java中ArrayList和LinkedList的遍歷與性能分析
- jQuery篩選數(shù)組之grep、each、inArray、map的用法及遍歷json對象
- C#常見的幾種集合 ArrayList,Hashtable,List<T>,Dictionary<K,V> 遍歷方法對比
- JavaScript中循環(huán)遍歷Array與Map的方法小結(jié)
- java arrayList遍歷的四種方法及Java中ArrayList類的用法
- java使用ArrayList遍歷及效率比較實例分析
- 數(shù)組Array進行原型prototype擴展后帶來的for in遍歷問題
- flex array 搜索 遍歷
- js中Array對象的常用遍歷方法詳解
相關(guān)文章
js中confirm實現(xiàn)執(zhí)行操作前彈出確認框的方法
這篇文章主要介紹了js中confirm實現(xiàn)執(zhí)行操作前彈出確認框的方法,是執(zhí)行刪除等操作時常用的功能,非常具有實用價值,需要的朋友可以參考下2014-11-11

