Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of jQuery.grep vs. Array.filter

In a question it was discussed on how jQuery and native JS would perform against each other.

While of course the vanilla solution performs a lot faster because it does not process the whole array I proposed the usage of Array.filter which I was pretty confident would be at least faster than $.grep.

Surprisingly after adding it to the test I was taught a lesson: Testsuite

Edgecases of course have a different outcome.

Anyone having an idea why $.grep is supposed to be over 3 times faster than the native method Arrray.filter?

Edit: I modified the test to use the filter shim from MDN and the results are pretty interesting:

  • Chrome: Even MDN shim is faster than the native method, jQuery way ahead
  • Firefox: shim a bit slower than native method, jQuery way ahead

and finally a result like i was hoping it to see in

  • Internet Explorer: native method is the fastest, then jQuery, shim is slowest (perhaps this is just the result of IEs rather weak JS-engine...)
like image 881
Christoph Avatar asked Feb 01 '13 13:02

Christoph


People also ask

What is difference between grep and filter in jquery?

The grep() method finds an element and the filter() method returns elements matching a specific criteria.

Is array filter faster than for loop?

To our surprise, for-loops are much faster than the Array. filter method. To be precise, the Filter method is 77% slower than for loop.

Which is faster filter or find?

find() here will be faster as your filter() method relies on find() anyway. From your code: var allCells = table.

Is filter function faster than for loop?

The difference between a built-in filter function and a for-in loop is not so obvious in this case. The build-in function is slightly faster (1.11x) than for-in loop.


1 Answers

As found on this blog post (which also does the same kind of tests):

If you read the documentation for filter, you will see why it's so much slower.

  1. It ignores deleted values and gaps in the array
  2. It optionally sets the execution context of the predicate function
  3. It prevents the predicate function from mutating the data
like image 79
MarcoK Avatar answered Sep 19 '22 06:09

MarcoK