Avoiding Recursion

Another common optimization technique that may speed up program execution and that definitely saves memory is to transform recursions into iterations. You can usually do so if there is only one simple recursion call. For example, the factorial of a number n is defined as n multiplied by the factorial of (n-1). The corresponding recursive function is

public static void fact (int n) {
    return n == 1 ? 1 : n * fact (n – 1);
}

The problem with recursion is that it consumes stack space: The return address and local variables are stored on the program stack when a method is called. Also, the program state changes that correspond to a method call might take more time than a simple loop.

Thus, for the function defined previously, ...

Get Java™ 2 Micro Edition Application Development 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.