Skip to content
Myr

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

6 files+119 added−30 removed

modified:perf-testing/immutability-benchmarks.mjs+2 added-2 removed
57 unmodified lines
58const MAX = 15960const 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 lines
modified:src/core/current.ts+9 added-3 removed
modified:src/core/finalize.ts+42 added-5 removed
54 unmodified lines
55function finalize(rootScope: ImmerScope, value: any, path?: PatchPath) {56 // Don't recurse in tho recursive data structures57 if (isFrozen(value)) return value5859 const useStrictIteration = rootScope.immer_.shouldUseStrictIteration()6061 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 lines
91 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 patches
17 unmodified lines
129 childValue: any,130 rootPath?: PatchPath,131 targetIsSet?: boolean132) {133 if (childValue == null) {134 return135 }136137 if (typeof childValue !== "object" && !targetIsSet) {138 return139 }140 const childIsFrozen = isFrozen(childValue)141 if (childIsFrozen && !targetIsSet) {142 return143 }144145 if (process.env.NODE_ENV !== "production" && childValue === targetObject)146 die(5)147 if (isDraft(childValue)) {148 const path =
14 unmodified lines
163 } 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 lines
modified:src/core/immerClass.ts+19 added-1 removed
29 unmodified lines
30 produce: IProduce31 produceWithPatches: IProduceWithPatches32}3334export type StrictMode = boolean | "class_only";34export type StrictMode = boolean | "class_only"3536export class Immer implements ProducersFns {37 autoFreeze_: boolean = true38 useStrictShallowCopy_: StrictMode = false39 useStrictIteration_: boolean = true4041 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 }5354 /**55 * The `produce` function takes a value and a "recipe function" (whose
119 unmodified lines
175 setUseStrictShallowCopy(value: StrictMode) {176 this.useStrictShallowCopy_ = value177 }178179 /**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 }188189 shouldUseStrictIteration(): boolean {190 return this.useStrictIteration_191 }192193 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: number
40 unmodified lines
modified:src/utils/common.ts+37 added-19 removed
33 unmodified lines
34 )35}3637const objectCtorString = Object.prototype.constructor.toString()38const cachedCtorStrings = new WeakMap()39/*#__PURE__*/40export 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 true4445 const Ctor =46 Object.hasOwnProperty.call(proto, "constructor") && proto.constructor4747 if (Ctor === Object) return true4850 return (51 typeof Ctor == "function" &&52 Function.toString.call(Ctor) === objectCtorString53 )49 if (typeof Ctor !== "function") return false5051 let ctorString = cachedCtorStrings.get(Ctor)52 if (ctorString === undefined) {53 ctorString = Function.toString.call(Ctor)54 cachedCtorStrings.set(Ctor, ctorString)55 }5657 return ctorString === objectCtorString58}5960/** Get the underlying object that is represented by the given draft */61/*#__PURE__*/
5 unmodified lines
6768/**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 */77export 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): void73export function each(obj: any, iter: any) {82export 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 lines
209export function freeze<T>(obj: T, deep?: boolean): T210export 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 freezing
5 unmodified lines
228function dontMutateFrozenCollections() {229 die(2)230}231232const dontMutateMethodOverride = {233 value: dontMutateFrozenCollections234}235236export 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