We have claimed twice now that reading ages[3] is instant no matter how big the array is. That claim should feel slightly suspicious — how can finding one slot among ten million take no longer than finding one among ten? This lesson shows the trick, and it is genuinely just arithmetic.
Recall from the memory-model lesson that memory is a long row of numbered slots, and that reading any address costs the same as reading any other. Add two design decisions from our array, and the trick falls out:
Given those three facts, the address of any element is a single multiplication and a single addition:
address of element i = base address + ( i x size of one element )Suppose our array begins at address 1000 and holds 4-byte integers. Element 0 sits at 1000. Element 1 sits four bytes later at 1004. Element 3 sits at 1000 + 3 x 4 = 1012.
Notice what the machine did not do: it never looked at elements 0, 1, or 2. It never scanned, compared, or searched. It multiplied, added, and read the result. That is three operations whether the index is 3 or 3,000,000 — which is precisely what O(1) means.
Several array rules that look arbitrary are really just consequences of that one formula:
ages[500] on a 108-element array happily computes an address and reads it. Nothing about the arithmetic knows your array ended — some languages check and throw, others hand you whatever bytes live there.This is the payoff of learning the memory model first. arr[i] is not a lookup — it is a calculation, and every characteristic of arrays follows from that fact.