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.
poke it, drag it,
try to break it
try to break it
no slides here.
you drive.
you drive.
Playground, this isn't a screenshot
measured on 200,000 items
push(x)add at the end
instant
pop()remove from the end
instant
arr[i]read a known position
instant
arr.lengthhow many
instant
shift()remove from the FRONT
3,861 ms
unshift(x)add at the FRONT
same problem
includes(x)is it in here?
checks every item
indexOf(x)where is it?
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