Loop order alone makes a 4096x4096 grid sum 13x slower due to CPU cache misses

A DEV Community author compared two functions that sum the same 4096 by 4096 grid, differing only in whether the outer loop walks rows or columns. Row-order summing took about 11 ms on an Apple M3 laptop, while column-order summing took about 146 ms, roughly 13 times slower. The explanation is that the CPU loads memory in fixed-size cache lines, so reading neighboring elements in a row reuses cached data, while jumping between rows in a column forces a memory fetch on nearly every read. The gap appears once the grid exceeds the cache size, and the author notes that a Float64Array shows the same pattern, indicating the cause is memory layout rather than JavaScript arrays. Suggested fixes include keeping the row loop outermost and accumulating column totals in a separate array, which matched the results of the column-order method at about 12 ms.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.


Discussion (0)
Log in to join the discussion and vote.
Log in