0
Challenge · 08Just Enough JavaScript

Array operations and their cost

JavaScriptused in ~100% of apps

Two lines of code can look equally innocent and one of them can be thousands of times slower. Nobody tells beginners this, so they write a correct solution, watch it fail on the big test, and have no idea why.

Core idea. Adding or removing at the END of an array is instant. Doing it at the START means every other item has to shift along, so the work grows with the size of the list. Same-looking code, wildly different cost.
Playground, this isn't a screenshot
measured on 200,000 items
push(x)
instant
pop()
instant
arr[i]
instant
arr.length
instant
shift()
3,861 ms
unshift(x)
same problem
includes(x)
checks every item
indexOf(x)
checks every item

Draining 200,000 items with shift() took 3,861 ms. Doing the same work without it took 1 ms.

↑ play a little first, then dig in