I ran some tests, and the data point that the jQuery inArray() is much slower than a simple loop.
And array.indexOf() is not even on the tests because I previously did other tests, and it performed even worse.
- Why it is much slower?
- Why don’t they use simple loops?
- Is there something that I am overseeing?
There must be a good reason for not using this:
for(var i=0,len=arr.length,rtn=-1;i<len;i++){
if(arr[i]==="arritem"){
rtn=i;
break;
}
}
If you’re going to test jQuery’s
inArray, actually test jQuery’sinArray, and compare apples to apples (calling a function to calling a function — you can write the loop inline in places where performance is hugely critical, but it wouldn’t be your default move, presumably): http://jsperf.com/inarraytest/3Preparation HTML:
Preparation code:
Tests:
Results on Chrome (which has
indexOf) are thatjQuery.inArrayis always faster thanarrayLoop(in the first pair of test cases, where we’re searching for the last entry, dramatically so).Results on IE6 (which doesn’t have
indexOf):jQuery.inArrayis always faster thanarrayLoop, though unsurprisingly not by much (as it has to do essentially the same work) — except, curiously, in the case where we’re searching for the first entry in the array, in which case it’s much faster.