Video in progress
What are range check elimination and loop unrolling, and how does the JIT speed up array loops?
Java must check the index bounds on every array access. C2 analyzes the loop and turns these checks into a single check before the loop (range check elimination), and it spreads the loop body into several copies to reduce the number of jumps (unrolling).
📖 Answer
By the semantics, a[i] checks 0 <= i < a.length every time, otherwise it throws ArrayIndexOutOfBoundsException. Over millions of iterations that is a noticeable cost.
long sum = 0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
}
Here C2 sees that i starts at 0, goes up by 1 and runs to a.length, so the check can never fail, and it removes it. In a more complex case (i < n, with n unknown) the loop is split: a pre-loop, the main part (without checks) and a post-loop. For the main part, the condition is checked once before the loop.
Unrolling: the body is repeated 4-8 times and the loop counter goes up by 4-8. Fewer conditional jumps, and the processor can execute instructions in parallel, which also lays the ground for vectorization.
What breaks these optimizations:
- a complex index expression (
a[idx[i]], indirect); - a
longloop counter (in older JDKslongloops were hardly optimized at all; around JDK 16 it improved a lot, butintis still more reliable); - a call inside the loop that isn't inlined;
- a
whilewhere the counter changes in several places.
The practical result: write hot loops in a plain, "boring" form: for (int i = 0; i < arr.length; i++). You can pull the work inside into small methods, and they will be inlined. In many cases the JIT gets close to C-level results from a well-written simple loop.
Sign up to mark studied questions and save your progress.