解決遍歷時Array.indexOf產生的性能問題
更新時間:2012年07月03日 11:47:36 作者:
javascript中數組是沒有indexOf方法,extjs中給數據添加了該方法
復制代碼 代碼如下:
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) ,所以,在數據量稍大的時候,需要尋找替代 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+']已存在');
}
});
您可能感興趣的文章:
- 詳談js遍歷集合(Array,Map,Set)
- Java中ArrayList和LinkedList的遍歷與性能分析
- jQuery篩選數組之grep、each、inArray、map的用法及遍歷json對象
- C#常見的幾種集合 ArrayList,Hashtable,List<T>,Dictionary<K,V> 遍歷方法對比
- JavaScript中循環(huán)遍歷Array與Map的方法小結
- java arrayList遍歷的四種方法及Java中ArrayList類的用法
- java使用ArrayList遍歷及效率比較實例分析
- 數組Array進行原型prototype擴展后帶來的for in遍歷問題
- flex array 搜索 遍歷
- js中Array對象的常用遍歷方法詳解
相關文章
Javascript實現關聯數據(Linked Data)查詢及注意細節(jié)
DBpedia對Wikipedia的數據變成Linked Data形式,使得機器也能讀懂并自由獲得這些數據;本文的主要目的是利用Javascript從DBpedia中獲取我們想要的數據,感興趣的朋友可以參考下,希望可以幫助到你2013-02-02javascript+html5+css3自定義彈出窗口效果
這篇文章主要為大家詳細介紹了javascript+html5+css3自定義彈出窗口效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10