Jason Knight
1 min readApr 10, 2023

--

A problem I see is that your removal method occurring inside the loop could in fact take even more time than reducing the count would/could save, just because how JavaScript handles arrays is ... well, slow.

For code clarity sake, I’d probably rewrite your first example thus:

const result = [];
for (let current of allItems) {
if (selectedItems.includes(current) result.push(current);
}

If I was throwing code clarity out the window for raw speed:

const result = [];
for (
let i = 0, current;
(current = allItems[i]) !== undefined;
i++
) {
if (selectedItems.includes(current)) result.push(current);
}

Might look weird if you’re not used to using the “full power of for and loose typing”, but it’s actually the fastest executing loop method.

I hate the various Array loop replacing methods becuase putting callbacks in the middle of a loop is just stupid. That’s overhead you shouldn’t be introducing and the only reason JS gets away with it is they’ve wasted time optimizing the crap out of that memory wasting nonsense, whilst leaving more sane and far clearer coding techniques to rot on the vine.

--

--

Jason Knight
Jason Knight

Written by Jason Knight

Accessibility and Efficiency Consultant, Web Developer, Musician, and just general pain in the arse

Responses (1)