Skip to content

Commit 53bb83f

Browse files
authored
perf: fast-path primitives in deepEnhancer (mobxjs#4683)
1 parent c9f2e3f commit 53bb83f

3 files changed

Lines changed: 25 additions & 0 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"mobx": patch
3+
---
4+
5+
perf: fast-path primitives in `deepEnhancer`. Writing a primitive into a deep observable no longer runs the observable/array/plain-object/Map/Set/function type checks; primitives can never be made observable, so they are returned immediately. Creating an observable array of primitives is ~4x faster, and observable Set/Map writes are ~20-25% faster in the perf suite.

packages/mobx/__tests__/base/makereactive.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -715,3 +715,18 @@ test("#1650, toString is not treated correctly", () => {
715715
const oo = mobx.observable(o)
716716
expect(oo.toString).toBe("toString")
717717
})
718+
719+
test("deep enhancer passes primitives through unchanged", () => {
720+
const x = mobx.observable({ v: undefined })
721+
const primitives = [1, "a", true, null, undefined, Symbol("test"), BigInt(42)]
722+
primitives.forEach(value => {
723+
x.v = value
724+
expect(x.v).toBe(value)
725+
})
726+
})
727+
728+
test("deep enhancer still wraps functions assigned after creation into autoActions", () => {
729+
const x = mobx.observable({ fn: undefined })
730+
x.fn = function () {}
731+
expect(mobx.isAction(x.fn)).toBe(true)
732+
})

packages/mobx/src/types/modifiers.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@ export interface IEnhancer<T> {
2222
}
2323

2424
export function deepEnhancer(v, _, name) {
25+
// primitives can never be made observable; skip the type checks below
26+
if (v === null || (typeof v !== "object" && typeof v !== "function")) {
27+
return v
28+
}
29+
2530
// it is an observable already, done
2631
if (isObservable(v)) {
2732
return v

0 commit comments

Comments
 (0)