DEV Community

Cover image for A Beginner's Guide: Memoization

A Beginner's Guide: Memoization

malik on July 28, 2018

This article was originally posted on malikbrowne.com. Last week, I was browsing different articles for guidance on the new lifecycle methods in ...
Collapse
 
ben profile image
Ben Halpern

It took me a while to understand memoization. I wish I'd had this guide!!

Collapse
 
milkstarz profile image
malik

I did too. If this helps one person struggle less than I did to understand this this post was worth the time. :)

Collapse
 
l_giraudel profile image
Loïc Giraudel

As a result, we can see that using the memoize technique in this solution would be a premature optimization - and would negatively impact the performance of our application.

While I agree about preventing premature optimization, on recursive functions like your factorial function memoization can store intermediate results, leading to optimized performance even if you don't call the function with the same parameter.

For instance, factorial(4999) could be faster if factorial memoizes all intermediate values from 4999 to 0. Of course, it means a bigger memory cost since the cache will no longer contain 1 value but 5000. But I think the best use case for memoization is on recursive pure functions.

The drawback is that you can't memoize a function from the outside like you did with memoize-one: the function must be implemented with its own cache.

Collapse
 
nickytonline profile image
Nick Taylor

A great example in React land is reselect. See their section on Motivation for Memoized Selectors.

Collapse
 
milkstarz profile image
malik

Reselect is great, and is probably one of the most popular tools used along with Redux.

A cool thing to note is that reselect allows you to pass in custom equality checks, or your own memoization function. I've played with it in the past - it's pretty cool.

Collapse
 
pnevares profile image
Pablo Nevares

Thanks for the great post malik. Awesome points about memory leaks!

Very small correction: Lehman's terms should be layman's terms

Collapse
 
milkstarz profile image
malik

ahhhh, thank you! i made the correction. :)

Collapse
 
marufalom profile image
Maruf Alom

Thank you so much. I am new in functional world

Collapse
 
teej profile image
TJ Fogarty

Ah this is fantastic, great write-up! I've always meant to learn more about this.

Collapse
 
milkstarz profile image
malik

Haha same here, figured I'd just write a blog post while I learned more about it too! :)

Collapse
 
anduser96 profile image
Andrei Gatej

Awesome post! Thank you!

Collapse
 
milkstarz profile image
malik

No problem, glad you liked it.