Sub topic 14
Readability Versus Performance: When a Loop Is the Better Choice
This chapter assumes you can already chain filter, map, and reduce into a pipeline, and that you can write a plain for or for...of loop. The question here is a practical one. When does a method chain cost more than it gives you, and when should you write a loop instead?
What a Chain Actually Does
Each array method finishes its whole pass before the next method starts. A chain of filter, map, and reduce therefore walks the data up to three times. It also builds two temporary arrays that are thrown away right after use.
const orders = Array.from({ length: 5 }, (_, i) => ({
id: i + 1,
total: (i + 1) * 10,
status: i % 2 === 0 ? 'paid' : 'pending'
}));
// Chain: three passes, two intermediate arrays
const chained = orders
.filter(o => o.status === 'paid')
.map(o => o.total)
.reduce((sum, t) => sum + t, 0);
// Loop: one pass, no intermediate arrays
let looped = 0;
for (const o of orders) {
if (o.status === 'paid') looped += o.total;
}
console.log(chained, looped); // 90 90With five orders the difference is too small to measure. With millions of rows, or with code that runs on every animation frame, the extra passes and allocations add work for the CPU and the garbage collector.
Early Exit Is the Bigger Win
map, filter, and reduce always visit every element, and they offer no break. A loop can stop as soon as it has what it needs.
const items = Array.from({ length: 1_000_000 }, (_, i) => i);
// Scans all one million items, then keeps three
const firstThreeChain = items.filter(n => n % 7 === 0 && n > 0).slice(0, 3);
// Stops after finding three
const firstThreeLoop = [];
for (const n of items) {
if (n % 7 === 0 && n > 0) {
firstThreeLoop.push(n);
if (firstThreeLoop.length === 3) break;
}
}
console.log(firstThreeChain, firstThreeLoop); // [7, 14, 21] [7, 14, 21]If you need only one match, find or some also stop early, so you can keep the method style. For "first N matches" or "stop when a running total passes a limit", a loop is the clearer tool.
Measure Before You Rewrite
Engines such as V8 run simple chains quickly, so check whether the chain is actually the slow part before you replace it.
const data = Array.from({ length: 2_000_000 }, (_, i) => i);
console.time('chain');
data.filter(n => n % 2 === 0).map(n => n * 2).reduce((a, n) => a + n, 0);
console.timeEnd('chain');
console.time('loop');
let sum = 0;
for (let i = 0; i < data.length; i++) {
if (data[i] % 2 === 0) sum += data[i] * 2;
}
console.timeEnd('loop');Timings depend on the engine and the machine. Run the comparison several times, and run it on realistic data, before you draw a conclusion.
Decision Guide
| Situation | Prefer |
|---|---|
| Small or medium arrays, ordinary app code | Method chain |
| Each step is a clear, named transformation | Method chain |
| Profiling shows the chain is a hot spot | Single loop |
| You need `break`, `continue`, or "first N" | Loop |
| You need `await` in sequence per element | `for...of` with `await` |
| One `reduce` callback has grown into many branches | Loop |
Folding the whole chain into one large reduce also gives you a single pass, but the callback often becomes harder to read than an equivalent loop. If you give up the chain for speed, write the loop plainly.
Exercise
A function scans a 5-million-row log array and must return the first 10 entries whose level is "error". It is currently written as logs.filter(l => l.level === 'error').slice(0, 10). Why is this slow, and what would you write instead?
Show answer
filter visits all 5 million rows and builds a full array of every error before slice keeps 10. Use a for...of loop that pushes matching entries into a result array and breaks once the array has 10 items. The loop stops early and never builds the large intermediate array.
Exercise
A teammate wants to rewrite a filter-map chain over a 50-item settings array as a for loop "for performance." What should you check first, and what is the likely outcome?
Show answer
Check whether profiling shows the chain is a measurable cost. With 50 items the extra pass and the temporary array cost almost nothing, so the rewrite makes the code harder to read with no real speed gain. Keep the chain.