Video in progress

How do you correctly compare ArrayList and LinkedList on iteration speed, and what does the result depend on?

In theory both are O(n), but in practice ArrayList is several times faster: the data sits contiguously in memory, and the CPU cache and prefetching work well. To compare correctly you need JMH, and you have to account for JIT warmup and the GC.

📖 Answer

Measuring a single loop with System.currentTimeMillis() gives a false number: the JIT hasn't compiled it yet, dead-code elimination may throw the result away, and the GC happens to land in the middle.

A minimal benchmark with JMH:

@State(Scope.Benchmark)
public class IterBench {
    @Param({"1000", "1000000"}) int size;
    List<Integer> array, linked;

    @Setup public void setup() {
        array = new ArrayList<>();
        for (int i = 0; i < size; i++) array.add(i);
        linked = new LinkedList<>(array);
    }
    @Benchmark public long arrayList()  { long s = 0; for (int v : array)  s += v; return s; }
    @Benchmark public long linkedList() { long s = 0; for (int v : linked) s += v; return s; }
}

The result is returned, so the JIT can't remove the loop.

What it depends on:

  • Size. If a small list fits in the L1/L2 cache, the difference is small. At a million elements LinkedList jumps to a different place in memory for every node, and the difference can reach 3 to 10 times.
  • How the objects are laid out in memory. Nodes created one after another sit side by side in the TLAB; in a long-running program, and after a GC, they can be scattered. So even in a benchmark, the "clean" state is more optimistic than reality.
  • The element itself. ArrayList<Integer> is really an array of references too, so you still jump to Integer objects. For truly linear memory, use int[].

Look at allocation with -prof gc as well. Before you show the number to others, write down the JDK version, the GC and the hardware. On another machine the result will change.