Occasionally Expensive, Usually Free
Last timeSpace Is a Cost As Well
Some operations are almost always instant and occasionally enormous. Averaging the enormous step over the cheap ones around it is the honest accounting, and it is why a growing list stays cheap.
Adding an item to the end of a list is instant. Except once in a while, when
it copies every item it holds into a larger block of memory.
So what does adding an item cost? The worst single add is linear in the whole
list, and saying so would be true and would describe nothing anybody
experiences.
| step | item added | room before | items copied | running total of copies |
|---|---|---|---|---|
| 1 | 1st | 1 | 0 | 0 |
| 2 | 2nd | 1 | 1 | 1 |
| 3 | 3rd | 2 | 2 | 3 |
| 4 | 5th | 4 | 4 | 7 |
| 5 | 9th | 8 | 8 | 15 |
| 6 | 17th | 16 | 16 | 31 |
| 7 | after 17 additions | 32 | 31 copies in total, under 2 per item |
- the number of items in the list at the end
- the total items copied across the entire history of the list
- the copying work charged to each addition once the total is shared out
What the averaged figure does not promise
It promises a total over a run. It does not promise anything about the one
addition that happened to be the one that copied.
For a service with a limit on every response, that distinction is the whole
problem: the rare quarter second copy is a breached limit no matter how good
the average is. The repairs are to spread the expensive work over the cheap
operations, a little at a time, or to do it in advance while nobody is
waiting. Both are common in systems that publish a worst case promise, and
both cost a little throughput to buy a steadier worst case.
The lesson stops here
1 more paragraph to go
You have read the opening. The rest of the argument, the problems that check whether it landed, and the lines worth keeping at the end all come with a plan.
The first lesson of every course in the library reads the whole way through, free, so you can see exactly what the rest of them are.
See the planThe contentsThis is the reading half
Starting the course gives you your own copy of it. Every idea on every page has problems standing under it, marked with a reason rather than a tick, and any sentence you do not believe can be opened and argued with. None of that can happen on a page nobody owns.
The contents