$.grep performance improvement
Hi there,
I'd like to propose a performance improvement to the "static method" jQuery.grep (1 code line and 1 comment line, just that):
$.grep = function(elems, callback, inv) {
// Returns using JS 1.6 native code, if appliable
if (Array.prototype.filter && !inv) return elems.filter(callback);
var ret = [];
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ )
if ( !inv != !callback( elems[ i ], i ) )
ret.push( elems[ i ] );
return ret;
};
If the client code doesn't use the "invert" argument, and the browser implements Array.prototype.filter, we can use the native method, since the signatures for this one and the $.grep callback are the same.
The difference - using 1000 iterations, and filtering a 1000 element array in each one -:
<span class="objectBox objectBox-text">- Old implementation: </span><span class="objectBox objectBox-text">929 ms
- New implementation: </span><span class="objectBox objectBox-text">812 ms
Conclusion: not that much of a performance boost, but as it's just 1 line of code, maybe it's </span><span class="objectBox objectBox-text"></span><span class="objectBox objectBox-text"></span>worth it... what do you guys think?<br clear="all">
--
Diogo Baeder
<a href="http://www.diogobaeder.com.br">http://www.diogobaeder.com.br</a>