January 2012
Intermediate to advanced
282 pages
7h 4m
English
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.
Listing 1–10. Using a Cache
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 ...