Space complexity
Five million ints is 18.9 MB and five million Integers is 95.4. Auxiliary space, the call stack that counts, and the trades you make on purpose.
Time complexity gets the attention. Space is the one that takes a service down, because running out of memory is not "slower" — it is a heap dump, a long garbage-collection pause, and then a process that is gone.
The same five million integers, two ways
### five million ints, two ways
### int[] 18.9 MB
### List<Integer> 95.4 MBFive times, for identical data, and nothing about the second version looks wasteful in the source. List<Integer> is what you write when you want a list of numbers.
The arithmetic is worth doing once, because it explains a whole family of surprises. An int[] is five million slots of four bytes, contiguous — about 20 MB, and the measurement agrees. A List<Integer> is:
- five million
Integerobjects, each with a header and a field — 16 bytes each on a 64-bit JVM with compressed references, so 80 MB; - plus a backing
Object[]of five million references at 4 bytes each — 20 MB.
So a hundred megabytes to hold twenty megabytes of numbers, and the extra eighty is object headers and pointers. The primitives and wrappers lesson establishes where those 16 bytes come from; this is what they cost at scale.
The three kinds of space, and only one is usually counted
When somebody says an algorithm is "O(1) space", they mean auxiliary space — extra memory beyond the input.
- Input space. The data you were given. Usually not counted, because you did not choose it.
- Auxiliary space. What the algorithm allocates itself. This is what O(1) or O(n) space refers to.
- The call stack. Counted, and routinely forgotten.
That last one is the one that bites, and it is the reason a recursive algorithm can be O(n) space when it allocates nothing at all:
long sum(int[] xs, int i) {
if (i == xs.length) return 0;
return xs[i] + sum(xs, i + 1); // no allocation, O(n) space
}Every call is a stack frame. A million elements is a million frames, and the result is a StackOverflowError — which, as the how-a-program-runs lesson explained, is a stack error rather than a heap one, and reports itself completely differently from running out of memory.
Java does not eliminate tail calls. Some languages turn that recursion into a loop; the JVM does not, and there is no flag that makes it. So in Java, recursion depth is a resource you are spending, and deep recursion over a large input is a loop waiting to be written.
The trade you make on purpose
Most of the interesting choices in this course are time bought with space:
| Technique | Space spent | Time bought |
|---|---|---|
a HashSet of seen ids | O(n) | O(n) → O(1) lookup |
| an index on a database column | disk | a scan → a seek |
| memoisation | O(states) | exponential → polynomial |
| a cache | bounded, chosen | a recomputation or a network call |
None is free, and stating the price is the part people skip. "Use a HashMap" costs a hash table the size of your data, and on a service with a heap budget that is a decision rather than a detail.
The reverse trade is rarer and real: streaming spends time to save space. Reading a file line by line is slower per element than having it all in memory, and it is the difference between a job that runs and a job that dies — which is the same argument the reading-input lesson made about BufferedReader.
What "in place" means, and what it costs
An in-place algorithm uses O(1) auxiliary space — it rearranges the input rather than building a copy.
Collections.sort(list); // sorts this list
List<T> sorted = list.stream() // builds a new one
.sorted().collect(toList());Both are O(n log n) in time. The second allocates a second list, and for a large collection that is a real cost.
But in-place is not automatically the right answer, and the reason is not performance: it destroys the original. If anything else holds a reference to that list, you have changed their data too — the pass-by-value lesson's point arriving as a memory decision. A copy is often worth its space precisely because it is a copy.
Measuring it, rather than reasoning about it
Reasoning gets you the shape. For an actual number:
- A heap dump and a tool that can read it — Eclipse MAT, VisualVM. It tells you what is there and what is holding it, which is usually the surprise.
-Xmxdeliberately low in a test, so the failure happens on your machine rather than in production.- JOL (Java Object Layout) for the size of one object, if the arithmetic above matters to a decision.
The measurement at the top of this lesson was taken the crude way — total memory before and after, with a garbage collection either side — and that is enough to see a factor of five. It is not enough to see a factor of 1.1, and knowing which question you are asking decides which tool you need.
Under the hood: what a stack frame actually is, and what ArrayList's growth actually copies
"The call stack counts" is easy to state and easy to leave abstract. Concretely: each thread gets its own stack, sized by -Xss (a HotSpot default around 512 KB–1 MB depending on platform and JDK), and every method call pushes a frame onto it — a fixed-size block holding the local variables array, an operand stack for intermediate values, and a bit of per-frame bookkeeping (the JVM specification, §2.6, defines the shape). A frame's size is decided at compile time from the method's bytecode, not at run time, which is why recursion depth before overflow is fairly predictable for a given method and JVM: divide the stack size by the frame size and that is roughly the ceiling the recursion lesson measures at 45,524.
The heap side has its own mechanics worth naming. A new object is not, in the common case, negotiated with a global allocator — each thread gets a TLAB (thread-local allocation buffer), a private slice of eden space it can bump-pointer allocate into with no synchronization at all, until the slice is full and a new one is requested. That is part of why allocation in Java is cheap relative to what it buys (an object header plus fields, as the boxing measurement above showed) — the cost people actually feel is not the allocation, it is the garbage collection that follows from doing it five million unnecessary times.
ArrayList's "amortised O(1)" is a copy, and the growth factor is fixed in the source, not a guess:
// java.util.ArrayList#grow, OpenJDK
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1); // 1.5x, not 2xEach grow allocates a new backing array 1.5 times the size and copies every existing element into it with Arrays.copyOf — an O(n) operation that happens O(log₁.₅ n) times as the list fills. The 1.5x factor (not doubling) is itself a space/time trade Sun made deliberately: a smaller growth factor wastes less memory on average between resizes, at the cost of resizing slightly more often. new ArrayList<>(expectedSize) skips every one of those copies by allocating the final-sized array up front — which is the space-complexity lesson's arithmetic turning into a one-argument constructor call.
Try it yourself
Size the stack budget by hand
A JVM thread stack is 512 KB (-Xss512k), and a particular recursive method's frame — its locals, its operand stack, its bookkeeping — comes to roughly 200 bytes once compiled. Roughly how many frames deep can this method recurse before StackOverflowError, and does that number square with the 45,524 measured in the recursion lesson (which almost certainly ran with a larger default stack)?
The division, and why the two numbers do not have to match exactly
512 KB is 524,288 bytes; divided by roughly 200 bytes per frame gives approximately 2,600 frames — an order of magnitude below the 45,524 the recursion lesson measured. That is not a contradiction: the two numbers assume different stack sizes (the recursion lesson's JVM was very likely running with a larger default, or a smaller per-frame method, than this hypothetical -Xss512k), and per-frame size depends entirely on how many locals the method declares and how deep its expression evaluation gets. The point of the exercise is the shape of the reasoning — stack budget divided by frame size gives an order-of-magnitude ceiling — not memorising either number. In practice this is also why -Xss is tuned up (not down) for code that recurses deeply on purpose, such as a hand-written recursive-descent parser over deeply nested input.
Misconceptions
- "A bigger
-Xmxfixes a space-complexity problem." It postpones the crash to a larger input, and buys time to fix the actual algorithm — it does not change O(n²) auxiliary space into O(n). The five-million-integer job still allocates five times more than it needs; it just does so with more headroom before it falls over. - "
Runtime.totalMemory() - Runtime.freeMemory()is what a heap dump would show." It is a coarse, GC-timing-dependent estimate — memory a collector has not yet reclaimed still counts as "used" by that formula, which is why the lesson's own measurement takes it either side of an explicit collection rather than trusting one snapshot.
Sources
- The Java Virtual Machine Specification, SE 21, §2.5–2.6 — frames, the Java Virtual Machine stack, and how a frame's structure is derived from a method's code.
- OpenJDK
java.util.ArrayListsource, thegrow()method — the 1.5x growth factor and theArrays.copyOfbehind every resize. - Java Object Layout (JOL) documentation, already the measurement tool this lesson recommends for object sizing.