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;
}
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.
No.
Sparingly.