This content originally appeared on DEV Community and was authored by Nikita Kozlov
Question:
What is memoization?
Quick answer:
It is a way to optimize application performance by caching results of time-consuming pure functions calculations.
Longer answer:
As we know from the previous post, there are pure and impure functions.
Pure functions are basically functions that return the same result if you pass the same data and they don't change anything outside of its scope.
let pureAdd = (a, b) => a + b
This pureAdd
function doesn't change anything outside it just returns the answer and it always returns the same answer for the same arguments.
With these restrictions come the benefits. If the result is the same every time we run the functions, then why don't we just calculate it once and save the result?
// Don't reuse it, it is just an example
let memo = (func) => {
let cache = {}
return (...args) => {
if (cache[args]) {
console.log('Cache hit :)')
return cache[args]
}
console.log('Cache miss :(')
let result = func(...args)
cache[args] = result
return result
}
}
function sleep(ms) {
var start = new Date().getTime(), expire = start + ms;
while (new Date().getTime() < expire) { }
return;
}
let slowAdd = (a, b) => {
sleep(1000)
return a + b
}
let memoAdd = memo(slowAdd)
console.log(memoAdd(1, 2))
// * waiting for 1 sec *
// Cache miss :(
// 3
console.log(memoAdd(1, 2))
// No waiting
// Cache hit :)
// 3
Real-life applications:
It's not only a theoretical benefit but actually a practical one.
For example, there is React.memo
which does memoization.
If your component renders the same result given the same props ... React will skip rendering the component, and reuse the last rendered result.
Also, there is a useMemo
hook, which also does memoization.
useMemo
will only recompute the memoized value when one of the dependencies has changed. This optimization helps to avoid expensive calculations on every render.
Resources:
wiki/memoization
react-docs
Other posts:
- JS interview in 2 minutes / pure vs impure functions
- JS interview in 2 minutes / Closure
- JS interview in 2 minutes / Currying ?
Btw, I will post more fun stuff here and on Twitter. Let's be friends ?
This content originally appeared on DEV Community and was authored by Nikita Kozlov
Nikita Kozlov | Sciencx (2021-05-26T11:55:48+00:00) JS interview in 2 minutes / Memoization ?. Retrieved from https://www.scien.cx/2021/05/26/js-interview-in-2-minutes-memoization-%f0%9f%92%ad/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.