Chapter 7. Loops, Switches, and Recursion
I have made this letter longer than usual because I lack the time to make it shorter.
This chapter describes performance-tuning a variety of common code structures: loops, switches, and recursion. Some of the tuning hints here are straightforward (for example, remove code from a loop if it is executed only once), but many are more esoteric, particularly given the subtleties of optimizations performed by HotSpot VMs and JIT compilers. Read on for details.
Loops
Programs spend most of their time in loops. There are many optimizations that can speed up loops, as detailed in the following sections.
Move Code Out of the Loop
Take out of the loop any code that does not need to be executed on every pass. This includes assignments, accesses, tests, and method calls that need to run only once.
Method calls are more costly than the equivalent code without the call, and by repeating method calls again and again, you just add overhead to your application. Move any method calls out of the loop, even if this requires rewriting. Inline method calls in loops when possible.
Use Temporary Variables
Array access (and assignment) always has more overhead than temporary variable access because the VM performs bounds-checking for array-element access. Array access is better done once (and assigned to a temporary) outside the loop rather than repeated at each iteration. For example, consider this next loop:
for(int i = 0; i < Repeat; i++) countArr[0]+=10; ...
Get Java Performance Tuning, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.