mobxjs / mobx

Simple, scalable state management.
http://mobx.js.org
MIT License
27.38k stars 1.76k forks source link

`trackDerivedFunction` pre-allocates memory for new deps array too aggressively #3834

Open realyze opened 5 months ago

realyze commented 5 months ago

trackDerivedFunction from packages/mobx/src/core/derivation.ts gets called every time a derivation is read (i.e., very often) and we currently preallocate 400 bytes (via new Array(100)) for the new dependencies array. This seems overly generous and can lead to more frequent garbage collection.

It depends on the app but arguably in the common case dependencies wouldn't change too wildly between derivation recomputations. So changing this to preallocating a constant memory space for initial deps array and then relative to the last run (e.g. 20% legroom for when dependencies change) seems reasonable.

As an example, I instrumented my local mobx build and in Canva when panning on a whiteboard (where we intersect elements with viewport), we overallocate space for the deps array by roughly 98% (i.e., we only use 2% of the memory we allocate, rest gets CG'd).

I took a stab at improving this in https://github.com/mobxjs/mobx/pull/3833 .

Intended outcome:

Actual outcome:

How to reproduce the issue:

Versions

realyze commented 5 months ago

Not really a "bug" but I wasn't sure where else to file this - please feel free to change the label!