Memoization with Closures
Cache expensive function results inside a closure-held table.
What Is Memoization?
Memoization caches the results of expensive function calls so that repeated calls with the same arguments return the cached result instantly.
Basic Memoize Wrapper
A closure holds a cache table. On first call, compute and store. On repeat calls, return the stored value.
local function memoize(fn)
local cache = {}
return function(x)
if cache[x] == nil then
cache[x] = fn(x)
end
return cache[x]
end
endAll lessons in this course
- What Are Upvalues?
- Shared Upvalues Between Closures
- Factory Functions and Generators
- Memoization with Closures