Amortized analysis
Intermediate · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Some operations are cheap almost always and expensive once in a while, like a growing list that sometimes has to move into a bigger home. Averaging that rare cost over many operations shows the real cost per step is still tiny, so you can use these tools without worry.
Practical use cases
- Web app: Building a big API response in a loop. A PHP script keeps adding rows to an array while reading 200,000 database records. Now and then the array silently grabs more memory and copies itself, which looks costly. Because that happens rarely, adding rows stays quick overall, so you do not need to pre-size anything or panic about append speed.
- Web app: Building a long string for a report. A page builds an HTML table by adding text piece by piece. Joining pieces in a growing buffer is cheap on average even though the buffer sometimes enlarges. The slow version rebuilds the whole text every time, so collecting pieces and joining once at the end keeps report generation fast.
- System: Hash tables resizing themselves. A hash table, the structure behind PHP associative arrays and JavaScript objects, occasionally doubles its space and re-files every item. That one step is slow, but it happens so seldom that each insert still averages out to a tiny cost. This is why using them freely is safe.
The story: The Shelf That Doubles
Raju's chai stall had a tiny shelf for tiffin boxes, with room for exactly one. When the second tiffin arrived, the shelf was full. Raju bought a bigger shelf, carried the old tiffin over, and put the new one beside it.
Mira saw the trouble. "Raju bhaiya, if you buy a shelf with just one more slot every time, you will carry every tiffin every time!" She was right: that is a lot of carrying. "Buy a shelf twice as big each time," she said.
Now moving day came rarely: when the shelf had 1, then 2, then 4, then 8 tiffins. Between moving days, adding a tiffin was a one-second job. Kabir did the accounts: "Yes, one push in a while is slow. But share that cost over all the quick pushes and the average is tiny."
That is amortized analysis: judging an operation by its average cost over a long run of operations, not by its single worst moment. Every dynamic array in your favourite language, PHP arrays and JS arrays included, plays this trick.
How to spot this problem, and where you need it
You see one occasional slow operation in a profile or a code review and wonder whether the whole feature is slow, or whether the rare spike is acceptable.
Signs you need it
- Timing graphs show mostly flat tiny steps with a rare tall spike, such as an array append that is sometimes slower.
- You are deciding whether it is safe to keep adding items to a list, buffer or counter in a long loop.
- A data structure promises fast on average but you are worried about the single worst call.
- A problem statement asks for the cost over a whole sequence of operations instead of one operation.
Where to use it in a project
- Judging whether stacks, queues and growing arrays are safe to use for millions of pushes in a background job.
- Deciding if a rare costly cache rebuild or table resize is acceptable, or must be spread out to avoid a visible freeze.
The solution
Add up the total work for a whole run of operations, then divide by the number of operations. If expensive steps happen rarely, for example each time the space doubles, their total stays small compared with the cheap steps, so the cost per operation is still tiny. If a single spike would hurt a user, such as a request that must always answer fast, spread the heavy work out or do it in the background.
Payoff: Before: worry that a rare slow append ruins a 200,000-row export. After: confidence that each append averages out to almost nothing.
Explain it like I am 8
Imagine a piggy bank where most days you drop in one coin, but every now and then you must count all coins into a bigger jar. Counting is slow, but it happens so rarely that, on average, each coin costs you just a couple of seconds.
How it works, step by step
- Start with a small array and add items one at a time, which costs 1 each when there is room.
- When it is full, make a new array of double the size and copy every item across. This one push is expensive.
- After doubling, the next many pushes have free room again, so they are cheap.
- Add up everything: all the copying over the whole run is less than twice the number of items.
- Divide by the number of pushes: the average (amortized) cost per push is a small constant, O(1).
The code in four languages
PHP
<?php
// A tiny growable array that counts how many item-copies it performs.
class GrowArray {
private array $slots;
private int $cap = 1;
private int $size = 0;
public int $copies = 0;
public function __construct() { $this->slots = array_fill(0, $this->cap, null); }
public function push($value): void {
if ($this->size === $this->cap) { // shelf is full: double it
$bigger = array_fill(0, $this->cap * 2, null);
for ($i = 0; $i < $this->size; $i++) {
$bigger[$i] = $this->slots[$i]; // move every old item
$this->copies++;
}
$this->slots = $bigger;
$this->cap *= 2;
}
$this->slots[$this->size++] = $value;
}
}
$a = new GrowArray();
$n = 1000;
for ($i = 0; $i < $n; $i++) $a->push($i);
echo "pushes: $n, copies: {$a->copies}
";
echo "work per push (amortized): " . round(($n + $a->copies) / $n, 2) . "
";JavaScript
// A tiny growable array that counts how many item-copies it performs.
class GrowArray {
constructor() {
this.cap = 1;
this.size = 0;
this.copies = 0;
this.slots = new Array(this.cap).fill(null);
}
push(value) {
if (this.size === this.cap) { // shelf is full: double it
const bigger = new Array(this.cap * 2).fill(null);
for (let i = 0; i < this.size; i++) {
bigger[i] = this.slots[i]; // move every old item
this.copies++;
}
this.slots = bigger;
this.cap *= 2;
}
this.slots[this.size++] = value;
}
}
const a = new GrowArray();
const n = 1000;
for (let i = 0; i < n; i++) a.push(i);
console.log("pushes: " + n + ", copies: " + a.copies);
console.log("work per push (amortized): " + ((n + a.copies) / n).toFixed(2));Java
import java.util.*;
public class Main {
// A tiny growable array that counts how many item-copies it performs.
static class GrowArray {
private int[] slots = new int[1];
private int cap = 1;
private int size = 0;
int copies = 0;
void push(int value) {
if (size == cap) { // shelf is full: double it
int[] bigger = new int[cap * 2];
for (int i = 0; i < size; i++) {
bigger[i] = slots[i]; // move every old item
copies++;
}
slots = bigger;
cap *= 2;
}
slots[size++] = value;
}
}
public static void main(String[] args) {
GrowArray a = new GrowArray();
int n = 1000;
for (int i = 0; i < n; i++) a.push(i);
System.out.println("pushes: " + n + ", copies: " + a.copies);
System.out.println("work per push (amortized): "
+ String.format(Locale.US, "%.2f", (double) (n + a.copies) / n));
}
}Go
package main
import "fmt"
// GrowArray is a tiny growable array that counts how many item-copies it performs.
type GrowArray struct {
slots []int
size int
copies int
}
func NewGrowArray() *GrowArray {
return &GrowArray{slots: make([]int, 1)}
}
func (a *GrowArray) Push(value int) {
if a.size == len(a.slots) { // shelf is full: double it
bigger := make([]int, len(a.slots)*2)
for i := 0; i < a.size; i++ {
bigger[i] = a.slots[i] // move every old item
a.copies++
}
a.slots = bigger
}
a.slots[a.size] = value
a.size++
}
func main() {
a := NewGrowArray()
n := 1000
for i := 0; i < n; i++ {
a.Push(i)
}
fmt.Printf("pushes: %d, copies: %d\n", n, a.copies)
fmt.Printf("work per push (amortized): %.2f\n", float64(n+a.copies)/float64(n))
}Time: O(1) amortized per push (O(n) for one unlucky push) · Extra space: O(n). All the copying over n pushes adds up to less than 2n, so each push averages a small constant.
Watch out for
- Confusing amortized with average case. Amortized is a guarantee over a whole sequence of operations, not a matter of luck or random input.
- Growing by a fixed amount (+1 or +10) instead of by a multiple. That brings back O(n) average work per push.
- Forgetting that one single push can still be slow, which matters in real-time systems.
Quick check
- Why does doubling the array make push cheap on average?
- Copying happens rarely, and each copy gets rarer as the array grows
- Copying becomes free
- The array never fills up
- If the shelf grew by just one slot each time, push would cost...
- O(1) on average
- About O(n) on average
- Nothing
- Amortized O(1) means...
- Every single push is exactly one step
- Over many pushes the average cost per push is a small constant
- The array is sorted