Sub topic 14
Readability Versus Performance: When a Loop Is the Better Choice
This chapter assumes you are comfortable with map, filter, reduce, and chaining them, as covered in earlier chapters. It also assumes you know basic for and for...of loops and async/await. The question here is a practical one. Array methods usually read better than loops, but sometimes a plain loop is faster, simpler, or the only correct tool. You will learn what a chain costs, when that cost matters, and how to decide.
What a Method Chain Actually Costs
A chain such as filter().map().reduce() reads as one pipeline, but the engine runs it as separate steps. Each step walks the whole array it receives. Every step except the last allocates a new array.
const orders = Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
total: (i + 1) * 10,
status: i % 2 === 0 ? 'paid' : 'pending'
}));
// Chain: three passes, two intermediate arrays
const revenueChain = orders
.filter(order => order.status === 'paid') // pass 1, new array of 3
.map(order => order.total) // pass 2, new array of 3
.reduce((sum, total) => sum + total, 0); // pass 3, single value
// Loop: one pass, no intermediate arrays
let revenueLoop = 0;
for (const order of orders) {
if (order.status === 'paid') revenueLoop += order.total;
}
console.log(revenueChain, revenueLoop); // 90 90Both versions give the same answer. The chain does more work: about 6 + 3 + 3 callback calls versus 6 loop iterations, plus two short-lived arrays for the garbage collector to clean up. Each callback is a function call. Modern engines such as V8 inline many of these calls, but they cannot always do so, and they never skip the intermediate arrays.
Why this usually does not matter
For a few hundred or even a few thousand elements, the difference is measured in microseconds. A single network request, DOM update, or JSON parse costs far more. In most application code, such as transforming an API response or preparing data for a UI component, the chain's clarity is worth much more than the time it costs.
Measuring Instead of Guessing
Do not rewrite a chain as a loop because it "feels slow." Measure first. The script below runs in Node.js 16+ and in browsers, both of which provide a global performance.now().
const data = Array.from({ length: 1_000_000 }, (_, i) => i);
function timeIt(label, fn, runs = 20) {
fn(); // warm-up run so the JIT compiler can optimize
const start = performance.now();
let result;
for (let i = 0; i < runs; i++) result = fn();
const ms = (performance.now() - start) / runs;
console.log(`${label}: ${ms.toFixed(2)} ms (result ${result})`);
}
timeIt('chain', () =>
data
.filter(n => n % 3 === 0)
.map(n => n * 2)
.reduce((sum, n) => sum + n, 0)
);
timeIt('loop', () => {
let sum = 0;
for (let i = 0; i < data.length; i++) {
const n = data[i];
if (n % 3 === 0) sum += n * 2;
}
return sum;
});On typical hardware the loop is often a few times faster for a million numbers. Exact ratios vary by engine, version, and data shape, so trust your own measurements, not someone's blog post.
Cases Where a Loop Wins
Raw speed is only one reason to choose a loop. Some cases are about correctness or about avoiding needless work.
Early exit
map, filter, and reduce always visit every element. If you can stop as soon as you find what you need, you should. find, some, and every already short-circuit, so use them first. A loop with break covers cases they do not fit, such as collecting items until a limit is reached.
const logs = ['ok', 'ok', 'warn', 'ERROR: disk', 'ok', 'ERROR: net'];
// Wasteful: filters the whole array, then keeps only the first
const firstErrorSlow = logs.filter(l => l.startsWith('ERROR'))[0];
// Better: find stops at the first match
const firstError = logs.find(l => l.startsWith('ERROR'));
// Loop: collect at most 2 non-ok entries, then stop
const firstTwoProblems = [];
for (const line of logs) {
if (line !== 'ok') firstTwoProblems.push(line);
if (firstTwoProblems.length === 2) break;
}
console.log(firstErrorSlow, firstError); // ERROR: disk ERROR: disk
console.log(firstTwoProblems); // ['warn', 'ERROR: disk']Accidental O(n²) inside reduce
The most common real performance bug with these methods comes from a pattern that looks tidy: copying the accumulator on every step with spread syntax.
const users = Array.from({ length: 5 }, (_, i) => ({ id: `u${i}`, name: `User ${i}` }));
// O(n²): each step copies every key collected so far
const slowIndex = users.reduce((acc, u) => ({ ...acc, [u.id]: u }), {});
// O(n): mutate the accumulator you created yourself
const fastIndex = users.reduce((acc, u) => {
acc[u.id] = u;
return acc;
}, {});
// Equally clear and also O(n)
const mapIndex = Object.fromEntries(users.map(u => [u.id, u]));
console.log(Object.keys(slowIndex).length, Object.keys(fastIndex).length, Object.keys(mapIndex).length); // 5 5 5With 10,000 users, the spread version makes roughly 50 million property copies. Mutating the accumulator is safe here because reduce created it from the {} initial value, and no other code holds a reference to it. Immutability matters for data other code shares. It does not apply to a local object you are still building.
Sequential async work
As the async chapter showed, map with an async callback starts every task at once. When tasks must run one after another, for example because of rate limits or because each step depends on the previous one, a for...of loop with await is the clearest correct option. A reduce over a promise chain can do the same job, but it is much harder to read.
const delay = (ms, value) => new Promise(resolve => setTimeout(() => resolve(value), ms));
async function processInOrder(ids) {
const results = [];
for (const id of ids) {
const value = await delay(10, id * 2); // waits before starting the next one
results.push(value);
}
return results;
}
processInOrder([1, 2, 3]).then(r => console.log(r)); // [2, 4, 6]Hot paths and very large data
Code inside a game loop, an animation frame, a parser, or a function that runs over millions of rows per request is where constant factors matter. Here, one fused loop with no intermediate allocations is a reasonable choice, as long as a profiler has shown that the code is hot.
Middle Ground: Keep the Style, Drop the Overhead
You do not have to choose between a three-step chain and a hand-written loop.
- Fuse steps.
flatMapcan filter and map in one pass: return[]to drop an element and[value]to keep it. A singlereducecan also filter, map, and sum together. - Use lazy iterator helpers. ES2025 added
Iterator.prototype.map,filter,take,reduce, and others. They process one element at a time through the whole pipeline and allocate no intermediate arrays. They ship in Node.js 22+ and current Chrome, Edge, Firefox, and Safari. Check your target environments before relying on them.
const nums = [1, 2, 3, 4, 5, 6, 7, 8];
// flatMap as filter + map in one pass
const doubledEvens = nums.flatMap(n => (n % 2 === 0 ? [n * 2] : []));
console.log(doubledEvens); // [4, 8, 12, 16]
// Lazy pipeline: stops after finding 2 matches, no intermediate arrays
if (typeof Iterator !== 'undefined' && Iterator.prototype.take) {
const firstTwo = nums.values()
.filter(n => n % 2 === 0)
.map(n => n * 2)
.take(2)
.toArray();
console.log(firstTwo); // [4, 8]
}Decision Guide
| Situation | Prefer | Reason |
|---|---|---|
| Typical app data (hundreds to low thousands of items) | Method chain | Clarity outweighs microseconds |
| Need the first match or a yes/no answer | `find`, `some`, `every` | Built-in early exit |
| Stop after a custom condition or limit | `for...of` with `break`, or iterator helpers with `take` | Array methods cannot break |
| Building an object or Map in `reduce` | Mutate the local accumulator | Spreading on each step is O(n²) |
| Async tasks that must run in order | `for...of` with `await` | `map` starts all tasks at once |
| Profiled hot path or millions of elements | Single fused loop | No intermediate arrays or callback overhead |
| Pipeline you want lazy without a loop | Iterator helpers | One pass, no intermediate arrays |
Readability Is Not Always on the Chain's Side
Chains are not automatically more readable. A reduce with a multi-line callback that tracks three accumulator fields is often harder to follow than a loop with three named variables. A chain of seven steps with nested ternaries is worse than a short loop. Judge by how fast a teammate can understand the code, not by how functional it looks. Naming intermediate results (const paidOrders = ...) often makes a chain readable again without giving up the method style.
Exercise
A teammate wrote const byId = items.reduce((acc, item) => ({ ...acc, [item.id]: item }), {}); for an array of 50,000 items, and the page freezes. Explain the cause and give two O(n) replacements.
Show answer
Each step spreads the whole accumulator into a new object, so step k copies k properties. That adds up to about n²/2 copies, roughly 1.25 billion for 50,000 items. Replacement 1: mutate the local accumulator, items.reduce((acc, item) => { acc[item.id] = item; return acc; }, {}). Replacement 2: Object.fromEntries(items.map(item => [item.id, item])), or new Map(items.map(item => [item.id, item])) if you want a Map.
Exercise
You need the first 10 products under $20 from an array of 200,000 products. Why is products.filter(p => p.price < 20).slice(0, 10) wasteful, and what are two better options?
Show answer
filter visits all 200,000 products and builds a possibly large intermediate array, but you only keep 10. Better option 1: a for...of loop that pushes matches into a result array and breaks when the array has 10 items. Better option 2: lazy iterator helpers, products.values().filter(p => p.price < 20).take(10).toArray(), which stop after the tenth match.
Exercise
Rewrite orders.filter(o => o.status === 'paid').map(o => o.total) so it makes one pass and still uses an array method.
Show answer
Use flatMap: orders.flatMap(o => (o.status === 'paid' ? [o.total] : [])). Returning an empty array drops the element, and returning a one-element array keeps the mapped value.