reselect icon indicating copy to clipboard operation
reselect copied to clipboard

WeakMap for memoization?

Open mockdeep opened this issue 9 years ago • 7 comments

Looking at some of the things we have to go through to handle somewhat confusing cases with selectors, I'm wondering if a WeakMap approach for the memoize function wouldn't help to side step some of the pain points. Instead of just memoizing one result per selector, period, we would memoize for any arguments that are still referenced from somewhere else and have the potential to end up getting passed into the selector again. I guess it would result in more memory consumption, but would naturally expire things when there was no possibility they would be used again. Does an approach like that make any sense?

mockdeep avatar May 18 '17 15:05 mockdeep

I have been thinking about something similar. Reselect is very stable, and I don't think we should change defaultMemoize right now, but it would be cool if someone wants to write up this approach for the docs or create a companion library.

ellbee avatar Jul 06 '17 18:07 ellbee

Sorry, forgot to say thanks for contributing the idea!

ellbee avatar Jul 06 '17 18:07 ellbee

I was hoping to find a way to use WeakMap in reselect sources, and was surprised to not find one.

The issue is, WeakMap doesn't work with primitive data types. In theory it would be possible to switch between Map and WeakMap, but you can't easily do that, because the type of an argument is known only after the call to memoized function, and it's not generally required to always be either object or primitive type, it can be a mixture of both. Given that there is no way to ensure that values of a Map will be collected when there is no more need in them, this approach doesn't really seem to be viable.

reverofevil avatar May 10 '22 04:05 reverofevil

Hmm. Hey @dai-shi , how does proxy-memoize do WeakMap stuff?

markerikson avatar May 10 '22 13:05 markerikson

Only with objects, it seems.

reverofevil avatar May 10 '22 14:05 reverofevil

Yes, and weak maps only work with objects.

https://github.com/dai-shi/proxy-memoize/blob/50689485bac20504086897d5bde7dae3ab548942/README.md?plain=1#L50-L57

dai-shi avatar May 11 '22 00:05 dai-shi

https://github.com/dagster-io/dagster/blob/6388276b94572df63b1adc095ddc148c1fdf351f/js_modules/ui-core/src/util/weakMapMemoize.ts#L69

salazarm avatar May 24 '26 02:05 salazarm