How Replacing a Loop with a Set Cut Page Load Time from 9s to 40ms
A developer discovered that a page loading in 80ms locally took 9 seconds in production — not due to a code bug, but because test data had only 60 rows while the production database held 14,000. The root cause was a duplicate-detection loop nested inside another loop, giving it O(n²) complexity, meaning operations scaled to 196 million at production size versus just 3,600 in testing. A subtler version of the same problem appeared with Array.includes() inside a loop, which looks like a single pass but secretly rescans the entire array each iteration. Replacing the inner scan with a JavaScript Set — which checks membership in O(1) constant time using a hash table — reduced the operation to a single linear pass. The fix required no caching or advanced optimization, illustrating how choosing the correct data structure based on Big O growth curves can dramatically improve real-world performance.
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