feat: Optimize Immer performance where possible, introduce `setUseStrictIteration` (#1164)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Use WeakMap caching implementation of isPlainObject * Add some early returns to `finalizeProperty` * Add `strictIteration` option * Add non-strict iteration handling * Use strict iteration option * Switch back to default strict iteration * Fix strict iteration checks * Shorten benchmark array sizes for faster results * Dedupe Map/Set method overrides * Removed old isPlainObject impl * Add early bailout to `isFrozen`
authored by Mark Erikson · committed by GitHub · parent 40aa814 · Browse files · 6 files·+119 added−30 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+119 added−30 removed
- other:+119 added−30 removed
Provenance
- Commit
e1996ce- Tree
ee58803- Author
Mark Erikson <mark@isquaredsoftware.com>- Committer
GitHub <noreply@github.com>- Parent
40aa814
6 files changed+119 added−30 removed
modified:perf-testing/immutability-benchmarks.mjs+2 added-2 removed
57 unmodified lines58 const MAX = 159 60 const BENCHMARK_CONFIG = {61 iterations: 1,62- arraySize: 10000,63- nestedArraySize: 100,62+ arraySize: 100,63+ nestedArraySize: 10,64 multiUpdateCount: 5,65 reuseStateIterations: 1066 }67 1154 unmodified linesmodified:src/core/current.ts+9 added-3 removed
19 unmodified lines20212223242526272829303132333435363334353738394041424344454619 unmodified linesfunction currentImpl(value: any): any { if (!isDraftable(value) || isFrozen(value)) return value const state: ImmerState | undefined = value[DRAFT_STATE] let copy: any let strict = true // Default to strict for compatibility if (state) { if (!state.modified_) return state.base_ // Optimization: avoid generating new drafts during copying state.finalized_ = true copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_) strict = state.scope_.immer_.shouldUseStrictIteration() } else { copy = shallowCopy(value, true) } // recurse each( copy, each(copy, (key, childValue) => { set(copy, key, currentImpl(childValue)) }) (key, childValue) => { set(copy, key, currentImpl(childValue)) }, strict ) if (state) { state.finalized_ = false } return copy}modified:src/core/finalize.ts+42 added-5 removed
54 unmodified lines55 function finalize(rootScope: ImmerScope, value: any, path?: PatchPath) {56 // Don't recurse in tho recursive data structures57 if (isFrozen(value)) return value58 59+ const useStrictIteration = rootScope.immer_.shouldUseStrictIteration()60+61 const state: ImmerState = value[DRAFT_STATE]62 // A plain object, might need freezing, might contain drafts63 if (!state) {64+ each(65+ value,62- each(value, (key, childValue) =>63- finalizeProperty(rootScope, state, value, key, childValue, path)66+ (key, childValue) =>67+ finalizeProperty(rootScope, state, value, key, childValue, path),68+ useStrictIteration69 )70 return value71 }72 // Never finalize drafts owned by another scope.18 unmodified lines91 resultEach = new Set(result)92 result.clear()93 isSet = true94 }90- each(resultEach, (key, childValue) =>91- finalizeProperty(rootScope, state, result, key, childValue, path, isSet)95+ each(96+ resultEach,97+ (key, childValue) =>98+ finalizeProperty(99+ rootScope,100+ state,101+ result,102+ key,103+ childValue,104+ path,105+ isSet106+ ),107+ useStrictIteration108 )109 // everything inside is frozen, we can freeze here110 maybeFreeze(rootScope, result, false)111 // first time finalizing, let's create those patches17 unmodified lines129 childValue: any,130 rootPath?: PatchPath,131 targetIsSet?: boolean132 ) {133+ if (childValue == null) {134+ return135+ }136+137+ if (typeof childValue !== "object" && !targetIsSet) {138+ return139+ }140+ const childIsFrozen = isFrozen(childValue)141+ if (childIsFrozen && !targetIsSet) {142+ return143+ }144+145 if (process.env.NODE_ENV !== "production" && childValue === targetObject)146 die(5)147 if (isDraft(childValue)) {148 const path =14 unmodified lines163 } else if (targetIsSet) {164 targetObject.add(childValue)165 }166 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.139- if (isDraftable(childValue) && !isFrozen(childValue)) {167+ if (isDraftable(childValue) && !childIsFrozen) {168 if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {169 // optimization: if an object is not a draft, and we don't have to170 // deepfreeze everything, and we are sure that no drafts are left in the remaining object171 // cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.172 // This benefits especially adding large data tree's without further processing.173 // See add-data.js perf test174 return175 }176+ if (177+ parentState &&178+ parentState.base_ &&179+ parentState.base_[prop] === childValue &&180+ childIsFrozen181+ ) {182+ // Object is unchanged from base - no need to process further183+ return184+ }185 finalize(rootScope, childValue)186 // Immer deep freezes plain objects, so if there is no parent state, we freeze as well187 // Per #590, we never freeze symbolic properties. Just to make sure don't accidentally interfere188 // with other frameworks.17 unmodified linesmodified:src/core/immerClass.ts+19 added-1 removed
29 unmodified lines30 produce: IProduce31 produceWithPatches: IProduceWithPatches32 }33 34-export type StrictMode = boolean | "class_only";34+export type StrictMode = boolean | "class_only"35 36 export class Immer implements ProducersFns {37 autoFreeze_: boolean = true38 useStrictShallowCopy_: StrictMode = false39+ useStrictIteration_: boolean = true40 41 constructor(config?: {42 autoFreeze?: boolean43 useStrictShallowCopy?: StrictMode44+ useStrictIteration?: boolean45 }) {46 if (typeof config?.autoFreeze === "boolean")47 this.setAutoFreeze(config!.autoFreeze)48 if (typeof config?.useStrictShallowCopy === "boolean")49 this.setUseStrictShallowCopy(config!.useStrictShallowCopy)50+ if (typeof config?.useStrictIteration === "boolean")51+ this.setUseStrictIteration(config!.useStrictIteration)52 }53 54 /**55 * The `produce` function takes a value and a "recipe function" (whose119 unmodified lines175 setUseStrictShallowCopy(value: StrictMode) {176 this.useStrictShallowCopy_ = value177 }178 179+ /**180+ * Pass false to use faster iteration that skips non-enumerable properties181+ * but still handles symbols for compatibility.182+ *183+ * By default, strict iteration is enabled (includes all own properties).184+ */185+ setUseStrictIteration(value: boolean) {186+ this.useStrictIteration_ = value187+ }188+189+ shouldUseStrictIteration(): boolean {190+ return this.useStrictIteration_191+ }192+193 applyPatches<T extends Objectish>(base: T, patches: readonly Patch[]): T {194 // If a patch replaces the entire state, take that replacement as base195 // before applying patches196 let i: number40 unmodified linesmodified:src/utils/common.ts+37 added-19 removed
33 unmodified lines34 )35 }36 37 const objectCtorString = Object.prototype.constructor.toString()38+const cachedCtorStrings = new WeakMap()39 /*#__PURE__*/40 export function isPlainObject(value: any): boolean {41 if (!value || typeof value !== "object") return false41- const proto = getPrototypeOf(value)42- if (proto === null) {43- return true44- }42+ const proto = Object.getPrototypeOf(value)43+ if (proto === null || proto === Object.prototype) return true44+45 const Ctor =46 Object.hasOwnProperty.call(proto, "constructor") && proto.constructor47-47 if (Ctor === Object) return true48 50- return (51- typeof Ctor == "function" &&52- Function.toString.call(Ctor) === objectCtorString53- )49+ if (typeof Ctor !== "function") return false50+51+ let ctorString = cachedCtorStrings.get(Ctor)52+ if (ctorString === undefined) {53+ ctorString = Function.toString.call(Ctor)54+ cachedCtorStrings.set(Ctor, ctorString)55+ }56+57+ return ctorString === objectCtorString58 }59 60 /** Get the underlying object that is represented by the given draft */61 /*#__PURE__*/5 unmodified lines67 68 /**69 * Each iterates a map, set or array.70 * Or, if any other kind of object, all of its own properties.67- * Regardless whether they are enumerable or symbols71+ *72+ * @param obj The object to iterate over73+ * @param iter The iterator function74+ * @param strict When true (default), includes symbols and non-enumerable properties.75+ * When false, uses looseiteration over only enumerable string properties.76 */77 export function each<T extends Objectish>(78 obj: T,71- iter: (key: string | number, value: any, source: T) => void79+ iter: (key: string | number, value: any, source: T) => void,80+ strict?: boolean81 ): void73-export function each(obj: any, iter: any) {82+export function each(obj: any, iter: any, strict: boolean = true) {83 if (getArchtype(obj) === ArchType.Object) {75- Reflect.ownKeys(obj).forEach(key => {84+ // If strict, we do a full iteration including symbols and non-enumerable properties85+ // Otherwise, we only iterate enumerable string properties for performance86+ const keys = strict ? Reflect.ownKeys(obj) : Object.keys(obj)87+ keys.forEach(key => {88 iter(key, obj[key], obj)89 })90 } else {91 obj.forEach((entry: any, index: any) => iter(index, entry, obj))117 unmodified lines209 export function freeze<T>(obj: T, deep?: boolean): T210 export function freeze<T>(obj: any, deep: boolean = false): T {211 if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj212 if (getArchtype(obj) > 1 /* Map or Set */) {201- Object.defineProperties(obj, {202- set: {value: dontMutateFrozenCollections as any},203- add: {value: dontMutateFrozenCollections as any},204- clear: {value: dontMutateFrozenCollections as any},205- delete: {value: dontMutateFrozenCollections as any}206- })213+ Object.defineProperties(obj, {214+ set: dontMutateMethodOverride,215+ add: dontMutateMethodOverride,216+ clear: dontMutateMethodOverride,217+ delete: dontMutateMethodOverride218+ })219 }220 Object.freeze(obj)221 if (deep)222 // See #590, don't recurse into non-enumerable / Symbol properties when freezing5 unmodified lines228 function dontMutateFrozenCollections() {229 die(2)230 }231 232+const dontMutateMethodOverride = {233+ value: dontMutateFrozenCollections234+}235+236 export function isFrozen(obj: any): boolean {237+ // Fast path: primitives and null/undefined are always "frozen"238+ if (obj === null || typeof obj !== "object") return true239 return Object.isFrozen(obj)240 }modified:src/immer.ts+10 added
70 unmodified lines71727374757677787980818283848586878841 unmodified lines70 unmodified lines immer)
/** * Pass false to use loose iteration that only processes enumerable string properties. * This skips symbols and non-enumerable properties for maximum performance. * * By default, strict iteration is enabled (includes all own properties). */export const setUseStrictIteration = /* @__PURE__ */ immer.setUseStrictIteration.bind( immer)
/** * Apply an array of Immer patches to the first argument. * * This function is a producer, which means copy-on-write is in effect. */41 unmodified lines