design-patternsimperative-programmingimperativeimperative-languages

What does it mean to convert a function to a table look up?


In this video titled Don't fear the monad, between 05:02 and 06:05, Brian Beckman says:

Every imperative programmer goes through this phase of learning that functions can be replaced with table look-ups. Often, you do this for performance. You want to make the sin function or the cosine function, just make a table and interpolate in that table....Everybody learns this trick.

I am wondering what he means by this trick and how it improves performance. Could you please elaborate?

Does it just mean having some sort of a look up like Dictionary<TKey, Func<TInput, TReturn>>?


Solution

  • It means that every algorithm, given enough (potentialy infinite) memory, can store precomputed output values based on input values in an (indexed) array, and thus convert the algorithm to O(1) array lookup. It's a trick as old as computing itself, predating computers by centuries. Scientists always used tables of precomputed values to get results quickly without doing actual computation.

    The Wikipedia article covering this topic is https://en.wikipedia.org/wiki/Lookup_table .

    BTW, many real-life algorithms (CRC comes to mind here) do it too, especially when speed is crucial (real-time applications). Note that the amount of memory needed to store the precomputed values is directly related to expected precision and amount of input variables.