1

I've had a question for a while. I know that the Array prototype method filter is generally preferred over forEach, and I believe it is typically faster at the job as well.

But what about if I have an array and I'm trying to partition each element into either bucket A or bucket B. Say array elements with property P are sorted into A.

This could be:

let A = inputArray.filter(element => element.P);
let B = inputArray.filter(element => !element.P);

But it could also be:

let A = [], B = [];
inputArray.forEach(element => {
  element.P ? A.push(element) : B.push(element);
});

where we only iterate over inputArray once. So which should be expected to be faster? I imagine there may be some delineation in the length of inputArray over which forEach begins to edge out two filters.

New contributor
Michael Jay is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1
4

This might be a case of pre-optimization. Each call to filter will loop over the array, so your first example iterates twice. Your second example iterates once. On the surface your second approach might be better, but if the array sizes are less than about 1,000 elements the difference in performance is likely negligible in modern browsers and mobile devices. If running this code in NodeJS on a server, then forget about optimizing the code at this point. You've got plenty of horse power.

Go for ease of maintenance and code readability first. Only after measuring a performance problem should you use the more obtuse and better performing code.

As an outside developer, seeing two separate calls to filter is much easier to understand. I would go for the first approach until you observe a tangible need for the second version.


As an aside, it took me a minute to read the ternary expression and realize you are testing a condition and then pushing items into two different arrays. Use a regular if-else statement here. Code obfuscastors and minifiers might turn it into a ternary expression for you. Then you can still get the smaller file size, but not at the expense of code readability.

1
  • someone has to pay for that extra electricity and keyboard wear and tear!! – Ewan Apr 8 at 9:36
3

I know that the Array prototype method filter is generally preferred over forEach

What makes you say that?

Filters and forEach are two different things; they are not interchangeable. There are situations where you'll use filter, and the ones where you'll use forEach.

I believe it is typically faster at the job as well

Don't believe something is faster. Measure it; this way you'll know.

So which should be expected to be faster? I imagine there may be [...]

Again, don't imagine. Performance is not about beliefs and what someone imagines. It's about exact measurements and hard data. You have your both approaches, and that's great. Now, you just have to run them side by side with the real data, and see which one outperforms the other.

Note the importance to use the real data. If the algorithm is expected to be used for the arrays containing about a dozen elements, don't compare the measurements using the arrays containing a billion elements. Similarly, if you want to run the algorithm on an array containing billions of elements, don't take measurements with an array containing a dozen elements, as the performance comparison would be perfectly irrelevant for your actual case.

4
  • 'filter() is slightly preferred because it is functional and should not mutate the original data.(yes, you can write it to do so if you are perverse). That said, you are correct, there are times you need forEach. Nor do I see why either would be particularly faster. – user949300 Apr 7 at 17:41
  • 2
    @user949300: filter filters stuff. forEach performs an action for the elements of an array. Those are two different things. Comparing map with forEach makes sense. Comparing filter with forEach doesn't. It has nothing to do with functional versus imperative programming either. If, for instance, you need to write a file line by line, you'll use forEach, and your code will still be functional. – Arseni Mourzenko Apr 7 at 18:55
  • Good catch, map is generally a better comparison to forEach. – user949300 Apr 8 at 0:39
  • you can imagine a javascript interpreter which is able to optimise the filters into a single loop and another which runs foreach loops twice, just to be sure. So 100% testing is the only way to know – Ewan Apr 8 at 9:34

Your Answer

Michael Jay is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.