Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use 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?

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?

like image 578
pr1001 Avatar asked Dec 10 '09 20:12

pr1001


3 Answers

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

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.

like image 86
Christian C. Salvadó Avatar answered Oct 11 '22 05:10

Christian C. Salvadó


What you really want is a Array.prototype.filter.

function findPoint(point, list)
{
     return list.filter(function anonFilterToId(p) { 
         return p.id === point.id; 
     }).length > 0;
}
like image 45
Raynos Avatar answered Oct 11 '22 05:10

Raynos


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:

like image 43
xtofl Avatar answered Oct 11 '22 07:10

xtofl