Skip to content
Myr

feat(performance): Make non-strict mode faster for classes. Addresses #1071

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Immer 10.x solved slow iteration for plain JS objects. This update applies the same handling to class instances. In cases this makes class instance handling 3 times faster. Note that this slightly modifies the behavior of Immer with classes in obscure corner cases, in ways that match current documentation, but do not match previous behavior. If you run into issues with this release icmw. class instances, use `setUseStrictShallowCopy("class_only")` to revert to the old behavior. For more details see https://immerjs.github.io/immer/complex-objects#semantics-in-detail

authored by Michel Weststrate · committed by GitHub · parents 9713677, 511ccee · Browse files · 5 files+118 added−68 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+118 added−68 removed

  • tests:+69 added−31 removed
  • other:+49 added−37 removed

5 files+118 added−68 removed

modified:__tests__/not-strict-copy.ts+69 added-31 removed
modified:src/core/immerClass.ts+8 added-3 removed
29 unmodified lines
30 produce: IProduce31 produceWithPatches: IProduceWithPatches32}3334export type StrictMode = boolean | "class_only";3536export class Immer implements ProducersFns {37 autoFreeze_: boolean = true36 useStrictShallowCopy_: boolean = false38 useStrictShallowCopy_: StrictMode = false3938 constructor(config?: {autoFreeze?: boolean; useStrictShallowCopy?: boolean}) {40 constructor(config?: {41 autoFreeze?: boolean42 useStrictShallowCopy?: StrictMode43 }) {44 if (typeof config?.autoFreeze === "boolean")45 this.setAutoFreeze(config!.autoFreeze)46 if (typeof config?.useStrictShallowCopy === "boolean")47 this.setUseStrictShallowCopy(config!.useStrictShallowCopy)
119 unmodified lines
167 * Pass true to enable strict shallow copy.168 *169 * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.170 */166 setUseStrictShallowCopy(value: boolean) {171 setUseStrictShallowCopy(value: StrictMode) {172 this.useStrictShallowCopy_ = value173 }174175 applyPatches<T extends Objectish>(base: T, patches: Patch[]): T {
43 unmodified lines
modified:src/utils/common.ts+35 added-29 removed
6 unmodified lines
7 AnyMap,8 AnySet,9 ImmerState,10 ArchType,11 die11 die,12 StrictMode13} from "../internal"1415export const getPrototypeOf = Object.getPrototypeOf16
123 unmodified lines
140 return state.copy_ || state.base_141}142143/*#__PURE__*/143export function shallowCopy(base: any, strict: boolean) {144export function shallowCopy(base: any, strict: StrictMode) {145 if (isMap(base)) {146 return new Map(base)147 }148 if (isSet(base)) {149 return new Set(base)150 }151 if (Array.isArray(base)) return Array.prototype.slice.call(base)152152 if (!strict && isPlainObject(base)) {153 if (!getPrototypeOf(base)) {154 const obj = Object.create(null)155 return Object.assign(obj, base)156 }157 return {...base}158 }153 const isPlain = isPlainObject(base)154160 const descriptors = Object.getOwnPropertyDescriptors(base)161 delete descriptors[DRAFT_STATE as any]162 let keys = Reflect.ownKeys(descriptors)163 for (let i = 0; i < keys.length; i++) {164 const key: any = keys[i]165 const desc = descriptors[key]166 if (desc.writable === false) {167 desc.writable = true168 desc.configurable = true169 }170 // like object.assign, we will read any _own_, get/set accessors. This helps in dealing171 // with libraries that trap values, like mobx or vue172 // unlike object.assign, non-enumerables will be copied as well173 if (desc.get || desc.set)174 descriptors[key] = {175 configurable: true,176 writable: true, // could live with !!desc.set as well here...177 enumerable: desc.enumerable,178 value: base[key]155 if (strict === true || (strict === "class_only" && !isPlain)) {156 // Perform a strict copy157 const descriptors = Object.getOwnPropertyDescriptors(base)158 delete descriptors[DRAFT_STATE as any]159 let keys = Reflect.ownKeys(descriptors)160 for (let i = 0; i < keys.length; i++) {161 const key: any = keys[i]162 const desc = descriptors[key]163 if (desc.writable === false) {164 desc.writable = true165 desc.configurable = true166 }167 // like object.assign, we will read any _own_, get/set accessors. This helps in dealing168 // with libraries that trap values, like mobx or vue169 // unlike object.assign, non-enumerables will be copied as well170 if (desc.get || desc.set)171 descriptors[key] = {172 configurable: true,173 writable: true, // could live with !!desc.set as well here...174 enumerable: desc.enumerable,175 value: base[key]176 }177 }178 return Object.create(getPrototypeOf(base), descriptors)179 } else {180 // perform a sloppy copy181 const proto = getPrototypeOf(base)182 if (proto !== null && isPlain) {183 return {...base} // assumption: better inner class optimization than the assign below184 }185 const obj = Object.create(proto)186 return Object.assign(obj, base)187 }181 return Object.create(getPrototypeOf(base), descriptors)188}189190/**191 * Freezes draftable objects. Returns the original object.
26 unmodified lines
modified:src/immer.ts+2 added-1 removed
modified:website/docs/complex-objects.md+4 added-4 removed
5 unmodified lines
6<center>7<div data-ea-publisher="immerjs" data-ea-type="image" className="horizontal bordered"></div>8</center>910By default, Immer does not strictly handle Plain object's non-eumerable properties such as getters/setters for performance reason. If you want this behavior to be strict, you can opt-in with `useStrictShallowCopy(true)`.1110Plain objects (objects without a prototype), arrays, `Map`s and `Set`s are always drafted by Immer. Every other object must use the `immerable` symbol to mark itself as compatible with Immer. When one of these objects is mutated within a producer, its prototype is preserved between copies.1112```js13import {immerable} from "immer"
44 unmodified lines
5859The semantics on how classes are drafted are as follows:60611. A draft of a class is a fresh object but with the same prototype as the original object.641. When creating a draft, Immer will copy all _own_ properties from the base to the draft.This includes non-enumerable and symbolic properties.621. When creating a draft, Immer will copy all _own_ properties from the base to the draft.This includes (in strict mode) non-enumerable and symbolic properties.631. _Own_ getters will be invoked during the copy process, just like `Object.assign` would.661. Inherited getters and methods will remain as is and be inherited by the draft.641. Inherited getters and methods will remain as is and be inherited by the draft, as they are stored on the prototype which is untouched.651. Immer will not invoke constructor functions.661. The final instance will be constructed with the same mechanism as the draft was created.671. Only getters that have a setter as well will be writable in the draft, as otherwise the value can't be copied back.6869Because Immer will dereference own getters of objects into normal properties, it is possible to use objects that use getter/setter traps on their fields, like MobX and Vue do.7071Note that, by default, Immer does not strictly handle object's non-enumerable properties such as getters/setters for performance reason. If you want this behavior to be strict, you can opt-in with `useStrictShallowCopy(config)`. Use `true` to always copy strict, or `"class_only"` to only copy class instances strictly but use the faster loose copying for plain objects. The default is `false`. (Remember, regardless of strict mode, own getters / setters are always copied _by value_. There is currently no config to copy descriptors as-is. Feature request / PR welcome).7273Immer does not support exotic / engine native objects such as DOM Nodes or Buffers, nor is subclassing Map, Set or arrays supported and the `immerable` symbol can't be used on them.7475So when working for example with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.