mobxjs / mobx-utils

Utility functions and common patterns for MobX
MIT License
1.18k stars 124 forks source link

Use a Map for createTransformer memoization #331

Open peterm-canva opened 4 weeks ago

peterm-canva commented 4 weeks ago

createTransformer() memoizes object transformations by creating a key for each possible input of type A, and then stores a mapping of that key to an object of type B in the context variable views. The key is stored on each A as a non-enumerable property named $transformId, so that each object can be looked up in the views cache later.

If we change views to be a Map instead of a plain object, we can get rid of the need for the IDs completely.

With this new impl, we still treat string and number inputs by value, and we still treat object inputs by identity. This comes down to the hashing semantics of Map.

This saves a small amount of memory in the unique memo IDs that were created for each input, and also some memory on each input object, which was modified to add the $transformId property. This may also have a performance benefit, because we aren't modifying the hidden shape of the inputs any more.

peterm-canva commented 4 weeks ago

@taj-p PTAL

peterm-canva commented 3 weeks ago

With this approach, we are retaining the input objects in the cache Map directly. With the previous approach we only kept the string IDs in the cache object. I don't think this is an issue, because the input objects are already retained by the computed() closure stored in the cache?

peterm-canva commented 2 weeks ago

@mweststrate PTAL when you have some time, thanks! 🙏