Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Big-O and Complexity

    Beyond Big-O

    Big-O is the most important tool, but not the only one:

    Chapter 11 of 112 min read

    Big-O is the most important tool, but not the only one:

    1. Constants matter for similar complexities. Two O(n) solutions can differ 10× in practice. In Part 0, sorting (O(n log n)) and the HashSet (O(n)) ran at nearly the same speed at these sizes — the HashSet does more work per element (boxing, hashing, objects — Classes, Objects and Memory Ch 8).

    2. Memory access patterns matter (How Computers Work Ch 6). Arrays walk the cache perfectly; pointer-heavy structures (linked lists, trees of objects) cause cache misses. This is why an O(n log n) array sort can beat an "O(n)" approach built on many small objects.

    3. Honest benchmarking in Java needs warm-up. The JIT compiles hot code while the program runs (How Computers Work Ch 8), so the first runs are slower. The measurements in this file ran each solution a few times before timing. Professional Java benchmarks use a tool called JMH.

    4. Measure growth, not single times. To check a complexity experimentally, time n, 2n, 4n and look at the ratio: ×2 → linear, ×4 → quadratic, slightly over ×2 → n log n. That's exactly what Part 0's table shows.