Caching Results
When computations are expensive, it may be a good idea to remember past results to make future requests faster. Using a cache is quite simple as it typically translates to the pseudo-code shown in Listing 1–10.
result = cache.get(n); // input parameter n used as key
if (result == null) {
// result was not in the cache so we compute it and add it
result = computeResult(n);
cache.put(n, result); // n is the key, result is the value
}
return result;
The faster recursive algorithm to compute Fibonacci terms yields many duplicate calculations and could greatly benefit from memoization. For example, computing the 50,000th term requires computing the 25,000th and 24,999 ...
Get Pro Android Apps Performance Optimization 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.