Home  >  Article  >  Web Front-end  >  Solve the performance problems caused by Array.indexOf during traversal_javascript skills

Solve the performance problems caused by Array.indexOf during traversal_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:52:041082browse
Copy code The code is as follows:

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;
}

As can be seen from the source code, the search is a simple linear search.
Since the linear search efficiency is O(n), when the amount of data is slightly larger, it is necessary to find an alternative to Array. There are many articles about this problem with Array, including "The Definitive Guide". The method is to simulate a Hash table.
The following is the problematic code
Copy the code The code is as follows:

var hostsIP = [];
Ext.each(_this.hosts,function(item){
hostsIP.push(item.ip);
});
Ext.each(txtHostsIP,function(ip) {
if(hostsIP.indexOf(ip)===-1){//Problem code
var host = {
isAppend: true,//New host
isAgentOk: false,
ip : ip
};
_this.hosts.push(
Ext.apply(host,_this.MAPPING_FIELDS)
);
isAppend = true;
}else {
errors.push('IP[' ip '] already exists');
}
});

When the hostsIP length exceeds 2000, IE8-browse The device will display the following prompt

Following the tips given in "The Definitive Guide", I made the following modifications to the code and the problem was solved.
Copy code The code is as follows:

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,//New host
isAgentOk : false,
ip : ip
};
_this.hosts.push(
Ext.apply(host,_this.MAPPING_FIELDS)
);
isAppend = true;
}else{
errors.push('IP[' ip ']already exists');
}
});
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn