作家
登录

解决遍历时Array.indexOf产生的性能问题

作者: 来源:www.28hudong.com 2013-03-30 00:26:36 阅读 我要评论

复制代码 代码如下: 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判断页面刷新或关闭的方法(onbeforeunload与onunload事件)

Onunload,onbeforeunload都是在刷新或关闭时调用,可以在<script>脚本中通过window.onunload来指定或者在<body>里指定。区别在于onbeforeunload在onunload之前执行,它还可以阻止onunload的执行。   Onbeforeun>>>详细阅读


本文标题:解决遍历时Array.indexOf产生的性能问题

地址:http://www.17bianji.com/kaifa2/JS/23286.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)