Should function memoization always be preferred?

1.8k views Asked by At

Recently I came upon function memoization.

I have read, that it can be used to optimise calls to functions that do some heavy computing, by caching it results if function parameters didn't change.

My question is, should I always use memoization wherever possible or only for functions with heavy computing operations?

I.e, I could use it also for simple function returning a boolean comparison, but won't it make more load? (importing library, using decorators, wrapping with memoize function etc.).

Example (random) function:

function isBigger(a: number, b: number) {
    return a > b;
}
2

There are 2 answers

0
onik On

function memoization is like caching. imagine you fetch a response from a server and put it into the cache, whenever you try to fetch the same data again you just get it from the cache, so you are making performance and memory optimization. it's the same case for function memorization, you pass some parameters and Javascript engine knows those same parameters return same answers..., so it's also performance and memory optimization. It's a cool feature, and there are cases, where memoization plays an important role. my advice is: use it if you can, and don't if it will make your code a mess

0
TylerR909 On

There are often several other optimizations you can make to your code before memoization becomes the thing that's worth doing. And if poorly implemented (or simply using shallow equality) it can lead to some difficult-to-detect bugs.

If, for example, a parameter is an array, and something new gets pushed into that array, it's still the same array. Shallow memoization would see the input didn't change (is the same array) and return the memoized value.

But anything other than Shallow could easily become just as expensive to run as whatever you're optimizing out.

So, sometimes it's useful but often times more hassle and clutter than it's worth. I use it in React to stop certain simple components from rerendering needlessly.

should I always use memoization wherever possible

No.

or only for functions with heavy computing operations?

Sparingly.