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
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
Provenance
- Commit
53e3203- Tree
5837063- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
9713677- Parent 2
511ccee
5 files changed+118 added−68 removed
modified:__tests__/not-strict-copy.ts+69 added-31 removed
1123456783459101112131478910111516171819202122232425262728293031131415161718192032222324333435362627282930373839404142434445464748495051525354555657585960616263646566676869707172733233343536377475import {produce, setUseStrictShallowCopy} from "../src/immer"import { immerable, produce, setUseStrictShallowCopy, setAutoFreeze, StrictMode} from "../src/immer"
describe("setUseStrictShallowCopy(true)", () => { test("keep descriptors", () => { setUseStrictShallowCopy(true)describe.each([true, false, "class_only" as const])( "setUseStrictShallowCopy(true)", (strictMode: StrictMode) => { test("keep descriptors, mode: " + strictMode, () => { setUseStrictShallowCopy(strictMode)
const base: Record<string, unknown> = {} Object.defineProperty(base, "foo", { value: "foo", writable: false, configurable: false const base: Record<string, unknown> = {} Object.defineProperty(base, "foo", { value: "foo", writable: false, configurable: false }) const copy = produce(base, (draft: any) => { draft.bar = "bar" }) if (strictMode === true) { expect(Object.getOwnPropertyDescriptor(copy, "foo")).toStrictEqual( Object.getOwnPropertyDescriptor(base, "foo") ) } else { expect(Object.getOwnPropertyDescriptor(copy, "foo")).toBeUndefined() } }) const copy = produce(base, (draft: any) => { draft.bar = "bar" }) expect(Object.getOwnPropertyDescriptor(copy, "foo")).toStrictEqual( Object.getOwnPropertyDescriptor(base, "foo") ) })})
describe("setUseStrictShallowCopy(false)", () => { test("ignore descriptors", () => { setUseStrictShallowCopy(false) test("keep non-enumerable class descriptors, mode: " + strictMode, () => { setUseStrictShallowCopy(strictMode) setAutoFreeze(false)
const base: Record<string, unknown> = {} Object.defineProperty(base, "foo", { value: "foo", writable: false, configurable: false class X { [immerable] = true foo = "foo" bar!: string constructor() { Object.defineProperty(this, "bar", { get() { return this.foo + "bar" }, configurable: false, enumerable: false }) }
get baz() { return this.foo + "baz" } }
const copy = produce(new X(), (draft: any) => { draft.foo = "FOO" })
const strict = strictMode === true || strictMode === "class_only"
// descriptors on the prototype are unaffected, so this is still a getter expect(copy.baz).toBe("FOObaz") // descriptors on the instance are found, even when non-enumerable, and read during copy // so new values won't be reflected expect(copy.bar).toBe(strict ? "foobar" : undefined)
copy.foo = "fluff" // not updated, the own prop became a value expect(copy.bar).toBe(strict ? "foobar" : undefined) // updated, it is still a getter expect(copy.baz).toBe("fluffbaz") }) const copy = produce(base, (draft: any) => { draft.bar = "bar" }) expect(Object.getOwnPropertyDescriptor(copy, "foo")).toBeUndefined() })}) })modified:src/core/immerClass.ts+8 added-3 removed
29 unmodified lines30 produce: IProduce31 produceWithPatches: IProduceWithPatches32 }33 34+export type StrictMode = boolean | "class_only";35+36 export class Immer implements ProducersFns {37 autoFreeze_: boolean = true36- useStrictShallowCopy_: boolean = false38+ useStrictShallowCopy_: StrictMode = false39 38- 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 lines167 * 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 }174 175 applyPatches<T extends Objectish>(base: T, patches: Patch[]): T {43 unmodified linesmodified:src/utils/common.ts+35 added-29 removed
6 unmodified lines7 AnyMap,8 AnySet,9 ImmerState,10 ArchType,11- die11+ die,12+ StrictMode13 } from "../internal"14 15 export const getPrototypeOf = Object.getPrototypeOf16 123 unmodified lines140 return state.copy_ || state.base_141 }142 143 /*#__PURE__*/143-export function shallowCopy(base: any, strict: boolean) {144+export 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)152 152- 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)154 160- 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 }189 190 /**191 * Freezes draftable objects. Returns the original object.26 unmodified linesmodified:src/immer.ts+2 added-1 removed
16 unmodified lines171819202121222324252689 unmodified lines16 unmodified lines isDraftable, NOTHING as nothing, DRAFTABLE as immerable, freeze, Objectish Objectish, StrictMode} from "./internal"
const immer = new Immer()
89 unmodified linesmodified:website/docs/complex-objects.md+4 added-4 removed
5 unmodified lines6 <center>7 <div data-ea-publisher="immerjs" data-ea-type="image" className="horizontal bordered"></div>8 </center>9 10-By 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)`.11-10 Plain 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.11 12 ```js13 import {immerable} from "immer"44 unmodified lines58 59 The semantics on how classes are drafted are as follows:60 61 1. A draft of a class is a fresh object but with the same prototype as the original object.64-1. When creating a draft, Immer will copy all _own_ properties from the base to the draft.This includes non-enumerable and symbolic properties.62+1. 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.63 1. _Own_ getters will be invoked during the copy process, just like `Object.assign` would.66-1. Inherited getters and methods will remain as is and be inherited by the draft.64+1. Inherited getters and methods will remain as is and be inherited by the draft, as they are stored on the prototype which is untouched.65 1. Immer will not invoke constructor functions.66 1. The final instance will be constructed with the same mechanism as the draft was created.67 1. Only getters that have a setter as well will be writable in the draft, as otherwise the value can't be copied back.68 69 Because 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.70 71+Note 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).72+73 Immer 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.74 75 So when working for example with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.