Make Your Javascript Code Faster with Memoization

Halil İbrahim Özdoğan
Nov 6 · 3 min read

Hi, in this article, we are going to look into memoization. And then we are going to learn how can we implement the memoization technique to our Javascript code.


For a kick-off, let’s check what is memoization.

Memoization is the technique that you can improve your application`s speed by caching results for expensive functions calls. For instance, we have a factorial function that calculates factorial of a given value. As we know that the factorial of a number is always the same, and never changes. 5! is always 120. If we calculate 5! once, we do not have to calculate it again. We can cache the result in the function scope. Then, whenever 5 is sent as a parameter, we can directly return the result from the cache. Thus, our code performance will be increased. The detailed code example is below.


Factorial Calculation Example

I run the example code by memoizing, either not memoizing in jsbench.ch

Non-Memoized Factorial Function
Memoized Factorial Function

The result can be able to see in the screenshot. The memoized code is approximately 50% faster than non-memoized depends on how many times you executed the function. The ratio might be differences according to the execution time of the function and computer hardware like CPU etc.

Memoized vs Non-Memoized Factorial Test
Memoized vs Non-Memoized Factorial Test

When the code has been executed 6 times, the ratio has been decreased which means the performance is increased by approximately 75%. Click to see the performance test.

CONCLUSION

When we applied this technique to the methods, the execution time of it decreases dramatically. Memoization works best with methods that may have heavy loads on it. You should be careful while using memoization since the output is cached after the first execution, the values that changing dynamically inside the method will be resulting in the same output with the same parameters.
We had implemented the technique to some functions in the project that I had been worked with Tugay İlik. We saw that general system performance has been improved almost 6x. I hope that you like the article.


Comments, shares, and discussions about the topic are always appreciated. I will be glad to help with any of your questions!

Feel free to contact me on Linkedin

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade