Performance Checklist

Most of these suggestions apply only after a bottleneck has been identified:

  • Make the loop do as little as possible.

    • Remove from the loop any execution code that does not need to be executed on each pass.

    • Move any code that is repeatedly executed with the same result, and assign that code to a temporary variable before the loop (“code motion”).

    • Avoid method calls in loops when possible, even if this requires rewriting or inlining.

    • Multiple access or update to the same array element should be done on a temporary variable and assigned back to the array element when the loop is finished.

    • Avoid using a method call in the loop termination test.

    • Use int data types preferentially, especially for the loop variable.

    • Use System.arraycopy( ) for copying arrays.

    • Try to use the fastest tests in loops.

    • Convert equality comparisons to identity comparisons when possible.

    • Phrase multiple boolean tests in one expression so that they “short circuit” as soon as possible.

    • Eliminate unneeded temporary variables from loops.

    • Try unrolling the loop to various degrees to see if this improves speed.

  • Rewrite any switch statements to use a contiguous range of case values.

  • Identify if a recursive method can be made faster.

    • Convert recursive methods to use iteration instead.

    • Convert recursive methods to use tail recursion.

    • Try caching recursively calculated values to reduce the depth of recursion.

    • Use temporary variables in place of passed parameters to convert a recursive method using a single search ...

Get Java Performance Tuning 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.