Memoization
Memoization is a programming technique to basically "cache" expensive procedures or operations in order to avoid evaluating their results again.
Take this function for example, to generate a character list starting from lowercase chars up to a certain character code:
1
local mem = {}
2
​
3
function generateCharlist(n)
4
if mem[n] then
5
return mem[n]
6
end
7
local str = ''
8
for i = 97, 97+n do -- start from lowercase
9
str = str .. string.char(i) -- convert number to character
10
end
11
mem[n] = str
12
return str
13
end
14
​
15
local firstList = generateCharlist(25) -- performs the generation
16
local secondList = generateCharlist(25) -- uses the pre-generated value
17
​
18
print(firstList, secondList) -- abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz
Copied!
Here once generateCharlist is called the first time, that string is generated and inserted into the mem table, the next time it runs with the exact same param as the first call, it will use the pre-generated value rather than having to spend the time generating it again.
Do not use that code as a good "optimized" example of that process (specifically lines 7-10), since I intended for it to perform poorly. More info about why this is awful to do can be found in the Optimizations page.
Last modified 2yr ago
Copy link