我应该使用jQuery.inArray()吗?

问题描述:

我在对象数组中进行非常频繁的搜索,并且一直在使用jQuery.inArray()。然而,我有速度和内存问题,根据我的分析器最常用的方法之一是jQuery.inArray()。这个词在街上有什么表现?我应该切换到一个简单的循环?

I'm doing very frequent searches in arrays of objects and have been using jQuery.inArray(). However, I'm having speed and memory issues and one of the most called methods according to my profiler is jQuery.inArray(). What's the word on the street about its performance? Should I switch to a simple for loop?

我的具体功能是:

function findPoint(point, list)
{
  var l = list.map(function anonMapToId(p) { return p.id });
  var found = jQuery.inArray(point.id, l);
  return found;
}

可能 list.map()更多的是责怪?

内部内部 inArray 做一个简单的循环,我建议您检查是否有原生的 Array.prototype.indexOf 实现并使用它而不是 inArray (如果可用):

Well internally inArray makes a simple loop, I would recommend you to check if there is a native Array.prototype.indexOf implementation and use it instead of inArray if available:

function findPoint(point, list) {
  var l = list.map(function anonMapToId(p) { return p.id });
  var found = ('indexOf' in Array.prototype) ? l.indexOf(point.id)
                                             : jQuery.inArray(point.id, l);
  return found;
}

Array.prototype.indexOf 方法已经在实现JavaScript 1.6的浏览器中引入,它将成为ECMAScript 5标准的一部分。

The Array.prototype.indexOf method has been introduced in browsers that implement JavaScript 1.6, and it will be part of the ECMAScript 5 standard.

本机实现是方式比非本地的。

Native implementations are way faster than non native ones.