Video in progress

Two pieces of code are both O(n), but one runs 10 times slower. What could the reasons be, and how do you measure?

long sumList(List<Integer> list) { long s = 0; for (int x : list) s += x; return s; }
long sumArray(int[] arr)         { long s = 0; for (int x : arr)  s += x; return s; }
// on 10 million elements sumList is several times slower

Big-O hides constant factors: boxing and pointer chasing, memory access that doesn't fit the CPU cache, branch misprediction, unnecessary allocation and GC. To measure, use JMH and then a profiler (async-profiler), not System.currentTimeMillis().

📖 Answer

An int[] is 4-byte numbers laid out contiguously in memory. The CPU fetches 16 of them in one cache line (64 bytes), the prefetcher pulls in the next one ahead of time, and the JIT can vectorize the loop.

An ArrayList<Integer> is an array of references. Each Integer is a separate object (~16 bytes) somewhere on the heap. For each element you follow a reference, unbox, and often take a cache miss. The data also takes 4-5 times more space.

Other frequent causes:

  • walking an int[][] by column is several times slower than by row, because every step touches a new cache line;
  • branch misprediction: on unsorted data if (x > 128) fools the CPU every time; the same code runs faster on a sorted array;
  • hidden allocation: stream(), lambda captures, String concatenation or an iterator inside a loop make the GC work;
  • in HashMap and LinkedList, every node is a separate object; LinkedList is almost never faster than ArrayList.

Measuring:

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
public class SumBench {
    int[] arr; List<Integer> list;
    @Setup public void init() {
        arr = new Random(1).ints(10_000_000).toArray();
        list = Arrays.stream(arr).boxed().toList();
    }
    @Benchmark public long array() { long s = 0; for (int x : arr) s += x; return s; }
    @Benchmark public long boxed() { long s = 0; for (int x : list) s += x; return s; }
}

You must return the result; otherwise the JIT can decide "nobody uses this sum" and remove the loop. If you measure by hand with nanoTime, warmup, JIT compilation and dead code elimination distort the result.

After that I look at allocation with -prof gc, and at CPU and cache misses with async-profiler. I don't optimize by guessing: whatever the measurement points at is what I fix.