dai-shi / proxy-memoize

Intuitive magical memoization library with Proxy and WeakMap

Home Page:http://proxy-memoize.js.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cache size understanding

Noitidart opened this issue · comments

I'm not understanding the cache size of proxy-memoize. How long does it hold on to the argument values is it forever?

Example:

memo(number => {
  return number + 10;
})

The number will always change. So does that mean it is never caching?

First things first, memoize only accepts one object.

It has a "result" cache, which is a weak map. So, it will remember the result for the same object forever.

const plusTen = memoize(obj => obj.num + 10);

const obj1 = { num: 1 };

plusTen(obj1); // running function
plusTen(obj1); // returning cached result
plusTen(obj1); // returning cached result

However, if you pass a fresh object, if will check it against "memo" cache.
The default size of the "memo" cache is 1 and can be configurable at creation.

const plusTenDefault = memoize(obj => obj.num + 10);

plusTenDefault({ num: 1 }); // running function
plusTenDefault({ num: 1 }); // returning memo'd result
plusTenDefault({ num: 2 }); // running function
plusTenDefault({ num: 2 }); // returning memo'd result
plusTenDefault({ num: 1 }); // running function again

const plusTenSize2 = memoize(obj => obj.num + 10, { size: 2 });

plusTenSize2({ num: 1 }); // running function
plusTenSize2({ num: 1 }); // returning memo'd result
plusTenSize2({ num: 2 }); // running function
plusTenSize2({ num: 2 }); // returning memo'd result
plusTenSize2({ num: 1 }); // returning memo'd result
plusTenSize2({ num: 3 }); // running function
plusTenSize2({ num: 1 }); // running function as the first one is gone

Oh this is so great thank you for this learning! This helps put together some great docs from the info in the issues!

Look forward to a PR then. Please try it first if it really works as expected. 😎

Haha for sure. I'm real keen on writing docs for this and jotai. Will definitely be in touch with the team! :)

Have you joined our discord servers?
Daishi's OSS: https://discord.gg/MrQdmzd
Poimandres: https://discord.gg/poimandres

Oh no I haven't! Thank you! Joining now