Using Memoization to Speed Up Code
xxpertHacker (649)

What is memoization?


Yeah, that's right, memo, not memor. I asked my self this when I first saw it. Simply put, memoization can be described as the caching of the results of a sub-step within an algorithm.

That makes it perfect for recursive functions, as they waste plenty of time recomputing everything, so that's what I tried it on, a recursive function.

And what recursive function is better known than a function to calculate the Fibonacci sequence?

After learning about memoization and how to do it, I spent hours perfecting a memoization wrapper which I then used on a JavaScript bigInt Fibonacci function.

I then laughed at the speed differences.

I calculated 1000 iterations of the Fibonacci sequence in 1 second. Without it, it took forever. You can try any number less than 200,000 without choosing to loop, and you'll receive an answer within 10 seconds, guaranteed or I'll refund you.

Try it out yourself!
https://MemoizedFibonacci.studentfires.repl.run


Some links I looked at:
https://www.freecodecamp.org/news/understanding-memoize-in-javascript-51d07d19430e
https://dictionary.babylon-software.com/dynamic%20optimization

You are viewing a single comment. View All
DynamicSquid (4532)

@StudentFires Yeah, now that I think about it, there isn't anything else you could be referring to when you said "variable argument functions". So anyway, I wrote this example:

#include <iostream>
using namespace std;

template<typename Result, typename ValueType>
void Sum(Result& result, ValueType& valueType)
{
	result += valueType;
}

template<typename Result, typename Current, typename... Next> // variadic template
void Sum(Result& result, Current currentValue, Next... valueN) // make sure the two functions have the same name
{
	result += currentValue;
	return Sum(result, valueN...);
}

int main()
{
	int answer = 0;
	Sum(answer, 10, 20, 30);
	cout << "The answer is " << answer;
}

So that's basically how to use a variadic function. I don't know how you're going to implement that, so this is all I can help with. Let me know if you have any questions.

Oh, and sorry for the massive indents, I wrote this on VS