From 6111b0939d0d3c0d46dc325ba6bbd5f740a161d3 Mon Sep 17 00:00:00 2001 From: Tomas Brambora Date: Thu, 7 Mar 2024 21:22:29 +1100 Subject: [PATCH] Reduce memory overhead of tracking (#3833) --- .changeset/swift-numbers-prove.md | 5 +++++ packages/mobx/src/core/derivation.ts | 9 ++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) create mode 100644 .changeset/swift-numbers-prove.md diff --git a/.changeset/swift-numbers-prove.md b/.changeset/swift-numbers-prove.md new file mode 100644 index 000000000..72e7d0f19 --- /dev/null +++ b/.changeset/swift-numbers-prove.md @@ -0,0 +1,5 @@ +--- +"mobx": patch +--- + +Reduce memory overhead of tracking dependencies diff --git a/packages/mobx/src/core/derivation.ts b/packages/mobx/src/core/derivation.ts index 70ee16959..252d18601 100644 --- a/packages/mobx/src/core/derivation.ts +++ b/packages/mobx/src/core/derivation.ts @@ -166,10 +166,13 @@ export function checkIfStateReadsAreAllowed(observable: IObservable) { */ export function trackDerivedFunction(derivation: IDerivation, f: () => T, context: any) { const prevAllowStateReads = allowStateReadsStart(true) - // pre allocate array allocation + room for variation in deps - // array will be trimmed by bindDependencies changeDependenciesStateTo0(derivation) - derivation.newObserving_ = new Array(derivation.observing_.length + 100) + // Preallocate array; will be trimmed by bindDependencies. + derivation.newObserving_ = new Array( + // Reserve constant space for initial dependencies, dynamic space otherwise. + // See https://github.com/mobxjs/mobx/pull/3833 + derivation.runId_ === 0 ? 100 : derivation.observing_.length + ) derivation.unboundDepsCount_ = 0 derivation.runId_ = ++globalState.runId const prevTracking = globalState.trackingDerivation