medikoo / memoizee

Complete memoize/cache solution for JavaScript
ISC License
1.73k stars 61 forks source link

How to clear cache on parameter change #55

Closed piotrblasiak closed 8 years ago

piotrblasiak commented 8 years ago

I want to use memoize with immutable.js and redux instead of reselect that the redux docs mention and I have the following use case which I think is very common:

The function signature:

function doSomething(state, param1, param2)

What is special about this function is that if the state changes, the whole cache should be cleared because it is a function that derives data from the current state of the app. One way I am thinking could solve this is to wrap this in a factory function just on the state and then cache that on the params. Something like:

memoize(state => memoize((param1, param2) => {...}))

Is this the best and perhaps only way to do it? And would this perform or is the memoize function call expensive? I know it´s a relative question and I should and will benchmark this but perhaps you already know the answer to this, especially the "is there a better way" one.

medikoo commented 8 years ago

@piotrblasiak Firstly, sorry for replying that late, Github notifications failed for me, and it's today I noticed that issue.

The second solution to me seems as the only option. Whether it's expensive relates to how often would that happen and how big save (of memory or CPU) is achieved by caching. Memoization, no matter how optimally implemented produces some overhead, so it may appear that for some really fast and light cases it's not worth pursuing, see e.g.: https://github.com/medikoo/memoizee/issues/27

Relating to first solution you consider. In here you actually want to clear cache that corresponds only to calls when first argument was of that given value. It's only possible if outside of memoize you tracked all that calls, having that you can clear them one by one. Doing that just via memoizee internals is not really possible, as there's no mechanism in memoizee (mainly for performance reasons) that will allow to investigate cache that way. Cache ids are plain strings, and it's hard to conclude for which one first argument was of given value.

I'm closing this, as I believe all is clear. Still feel free to continue discussion here