views:

408

answers:

2

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?

My specific function is:

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

Is perhaps list.map() is more to blame?

+3  A: 

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 avalable:

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

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.

CMS
A: 

Even is the inArray function were slow, you're still creating a full new array for every search. I suppose it would be better to redesign this search, by e.g. creating the id-list before finding the points, and using that one to search into:

xtofl