In jQuery is it more efficient to use filter(), or just do so in the each()?

James Skemp picture James Skemp · May 8, 2011 · Viewed 15k times · Source

I currently have code that is pulling in data via jQuery and then displaying it using the each method.

However, I was running into an issue with sorting, so I looked into using, and added, jQuery's filter method before the sort (which makes sense).

I'm now looking at removing the sort, and am wondering if I should leave the filter call as-is, or move it back into the each.

The examples in the jQuery API documentation for filter stick with styling results, not with the output of textual content (specifically, not using each()).

The documentation currently states that "[t]he supplied selector is tested against each element [...]," which makes me believe that doing a filter and an each would result in non-filtered elements being looped through twice, versus only once if the check was made solely in the each loop.

Am I correct in believing that is more efficient?

EDIT: Dummy example.

So this:

// data is XML content
data = data.filter(function (a) {
    return ($(this).attr('display') == "true");
});
data.each(function () {
    // do stuff here to output to the page
});

Versus this:

// data is XML content
data.each(function () {
    if ($(this).attr('display') == "true") {
        // do stuff here to output to the page
    }
});

Answer

Erick Petrucelli picture Erick Petrucelli · May 8, 2011

Exactly as you said:

The documentation currently states that "the supplied selector is tested against each element [...]", which makes me believe that doing a filter and an each would result in non-filtered elements being looped through twice, versus only once if the check was made solely in the each loop.

Through your code we can clearly see that you are using each in both cases, what is already a loop. And the filter by itself is another loop (with an if it for filtering). That is, we are comparing performance between two loops with one loop. Inevitably less loops = better performance.

I created this Fiddle and profiled with Firebug Profiling Tool. As expected, the second option with only one loop is faster. Of course with this small amount of elements the difference was only 0.062ms. But obviously the difference would increase linearly with more elements.

Since many people are super worried to say the difference is small and you should choose according to the maintainability, I feel free to express my opinion: I also agree with that. In fact I think the more maintainable code is without the filter, but it's only a matter of taste. Finally, your question was about what was more efficient and this is what was answered, although the difference is small.