Solve the performance problem caused by the time-elapsed Array. indexOf.

Source: Internet
Author: User

Copy codeThe 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
* @ 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;
}

From the source code, we can see that the search is a simple linear search.
Because the linear search efficiency is O (n), when the data volume is slightly larger, we need to find a method to replace Array. Many articles have mentioned this issue about Array, including the authoritative guide, by simulating a Hash table.
Below is the problematic code
Copy codeThe 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, the following prompt appears in the IE 8-Browser:

As prompted in the authoritative guide, I fixed the problem after modifying the Code as follows.
Copy codeThe 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 ');
}
});

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.