Caching and why it is important

So this is going to be a short tutorial and will just be talking about why you should cache and a basic example on how you can.

Alright so if for some reason you have a program which detects the Fibonacci sequence (don’t ask why I have this)

As a bench mark I added in a goes variable to see how many times the function was called

local Goes = 0


local function Fibonacci(n)
	
	Goes += 1
	
	if not tonumber(n) then
		return
	else
		n = tonumber(n)

	end

	if n == 0 then return n end

	if n == 1 then return n end

	return Fibonacci(n-1,cache) + Fibonacci(n-2,cache)  

end

Fibonacci(10)

print(Goes)

And it uses recursion. (This is applicable to most other functions which use a recursion type)

Then it it great for small things like 10 however is called 177 times!

And if I put this up to 25 my script times out!

An answer to this would be caching

Now the definition of caching is this: Caching is the process of storing copies of files in a cache, or temporary storage location, so that they can be accessed more quickly

but that could be simplified to: Easy place for me to get repeated values

If I just added that into my code:

local Goes = 0

local function Fibonacci(n,cache)
	
	Goes += 1
	
	if not tonumber(n) then
		return
	else
		n = tonumber(n)

	end

	if n == 0 then return n end

	if n == 1 then return n end
	
	if cache[n] then
		return cache[n]
	end
	
	cache[n] = Fibonacci(n-1,cache) + Fibonacci(n-2,cache)  
	
	return Fibonacci(n-1,cache) + Fibonacci(n-2,cache)  

end

Fibonacci(10,{})

print(Goes)

The function is only called 37 times.

I did it with 100 and only did it 397 times!. With an extra 5 or so lines I managed to save so much performance.

So in conclusion caching is good because it saves space, performance and makes recursive scripts more effective

Alright that’s it. I did say it would be short and just wanted to show the benefits of it.

Thanks for reading :slight_smile:

2 Likes