liveBook · Manning

Caching

As explained in Modern C, Third Edition

A cache is storage that retains previously computed values so they can be reused instead of recomputed.

Caching retains previously computed values so recursive calls can reuse them instead of repeating the same computation. It trades storage for computation time. section 7.3

Caching Fibonacci results

The naive recursive fib function recomputes calls such as fib(2), producing exponential execution time. fibCacheRec stores each computed Fibonacci value in an array and computes it only when the corresponding cache entry is empty, reducing execution time to linear in n. section 7.3

/* Compute Fibonacci number n with the help of a cache that may
   hold previously computed values. */
size_t fibCacheRec(size_t n, size_t cache[static n]) {
  if (!cache[n-1]) {
    cache[n-1]
      = fibCacheRec(n-1, cache) + fibCacheRec(n-2, cache);
  }
  return cache[n-1];
}

size_t fibCache(size_t n) {
  if (n+1 <= 3) return 1;
  /* Set up a VLA to cache the values. */
#if __STDC_VERSION__ > 202311L
  /* Since C23, VLA can be default initialized. */
  size_t cache[n] = { };
#else
  size_t cache[n]; memset(cache, 0, n*sizeof(*cache));
#endif
  /* Non-trivial initialization is replaced by assignment. */
  cache[0] = 1; cache[1] = 1;
  /* Call the recursive function. */
  return fibCacheRec(n, cache);
}

Inspect the complete C implementation, including cache setup, base values, recursive lookup, and C23-versus-pre-C23 VLA initialization. section 7.3

TAKEAWAY

  • Improve the algorithm before relying on implementation cleverness: changing exponential recursion to cached recursion can dramatically improve performance. section 7.3

How Modern C, Third Edition covers it

How deep it goes
Explains cache lookup, storage, initialization, and linear-time behavior, but stops short of concrete performance measurements.
Examples
Demonstrates caching through recursive Fibonacci computation using an array of previously computed values.
What it assumes
Assumes familiarity with recursive functions and arrays while demonstrating repeated subcomputations and storage-based optimization.
What you can do after
Build it from scratch by adding an array cache to recursive Fibonacci and reasoning about its linear execution time.
How it connects
Connects caching with recursion, algorithms, execution time, storage, and variable-length arrays.

Also explained in

Compare how 38 books explain caching →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.