DEV Community

Discussion on: Start using memoization to reduce computing time in Javascript

Collapse
 
thekashey profile image
Anton Korzunov

That was in the part about "One Result" - it's hard to remember more that one (last) result. Let's double check your examples:

fibonacci

function fib(n) {
  if (n === 0 || n === 1)
    return n;
  else
    return fib(n - 1) + fib(n - 2);
}
  • How much cache size need - n
  • How much size it would take - almost nothing
  • Do we need persistent cache? - Well yes, but even non persistent cache would be ok.
function fib(n, cache) {
+  if(!cache) cache = {};
  if (n === 0 || n === 1)
    return n;
  else
+    return cache[n] = (fib(n - 1, cache) + fib(n - 2, cache));
 }

Now every fibonacci run would have it's own unique cache. It would be not so far (faaar not so fast), but a bit more safe.

PS: fibonacci is not the great example for this, and the "safe" could be more sound in the real solutions.

cached

So - first of all caching is not memoization :) Anyway

function cached (fn) {
  var cache = Object.create(null);
  return (function cachedFn (str) {
    var hit = cache[str];
    return hit || (cache[str] = fn(str))
  })
}
  • What would happen a day after? How many strings this cache would hold?
  • Keep in mind - v8 has an everlasting bug (actually a feature), when a whole string would be "protected" from garbage collecting if some substring is used - bugs.chromium.org/p/v8/issues/deta...
  • So - any "cache" might just ruin your server or SPA after just "some time".

It's still easy to fix the problem (just stringify strings) but in this case you will run into out-of-memory in any way, as long as there is no cache invalidation, eviction or expiration defined.

I hope you remember - cache invalidation is one of 3 most complex problems in the universe, so... still not a big problem - dozens of LRU caches could be found at npm, even I wrote at least 3 😅.

But the problem is - you have to think what exactly you need, why, how would it help, how to control and monitor that new thing...

Have a good day :)