Merge pull request #38 from mweststrate/feature/performance
Before adoption: this commit came in with the history the project adopted, so no landing records it.
improve performance
authored by Michel Weststrate · committed by GitHub · parents cc61e1e, e49d0a2 · Browse files · 9 files·+401 added−304 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+401 added−304 removed
- tests:+40 added−9 removed
- other:+361 added−295 removed
Provenance
- Commit
670fcff- Tree
50ea6ac- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
cc61e1e- Parent 2
e49d0a2
9 files changed+401 added−304 removed
modified:__performance_tests__/todo.js+88 added-22 removed
123456789101112131415169 unmodified lines26272829242526272829303130313233346 unmodified lines414243444546464748495051525354555657585960616263646566486768697052717273747576777859798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133787980818283841341351361371381391401411421431441454 unmodified lines1501511521539798991541551561571581591607 unmodified lines168169170171172173174175176177178179180181"use strict"import immerProxy, {setAutoFreeze as setAutoFreezeProxy} from ".."import immerEs5, {setAutoFreeze as setAutoFreezeEs5} from "../es5"import cloneDeep from "lodash.clonedeep"import {List, Record} from "immutable"import deepFreeze from "deep-freeze"
function freeze(x) { Object.freeze(x) return x}
describe("performance", () => { const MAX = 100000 const MODIFY_FACTOR = 0.1 const baseState = []9 unmodified lines }) }
// Produce the frozen bazeState frozenBazeState = baseState.map(todo => { const newTodo = {...todo} newTodo.someThingCompletelyIrrelevant = todo.someThingCompletelyIrrelevant.slice() Object.freeze(newTodo.someThingCompletelyIrrelevant) Object.freeze(newTodo) return newTodo }) Object.freeze(frozenBazeState) frozenBazeState = deepFreeze(cloneDeep(baseState))
// generate immutalbeJS base state const todoRecord = Record({ todo: "",6 unmodified lines global.gc && global.gc() test(name, fn) }
{ const draft = cloneDeep(baseState) measure("just mutate", () => { measure("just mutate", () => { for (let i = 0; i < MAX * MODIFY_FACTOR; i++) { draft[i].done = true } }) }
{ const draft = cloneDeep(baseState) measure("just mutate, freeze", () => { for (let i = 0; i < MAX * MODIFY_FACTOR; i++) { draft[i].done = true } deepFreeze(draft) }) }
measure("deepclone, then mutate", () => { const draft = cloneDeep(baseState) for (let i = 0; i < MAX * MODIFY_FACTOR; i++) { baseState[i].done = true draft[i].done = true } })
measure("deepclone, then mutate", () => { measure("deepclone, then mutate, then freeze", () => { const draft = cloneDeep(baseState) for (let i = 0; i < MAX * MODIFY_FACTOR; i++) { draft[i].done = true } deepFreeze(draft) })
measure("handcrafted reducer", () => { measure("handcrafted reducer (no freeze)", () => { const nextState = [ ...baseState.slice(0, MAX * MODIFY_FACTOR).map(todo => ({ ...todo, done: true })), ...baseState.slice(MAX * MODIFY_FACTOR) ] })
measure("handcrafted reducer (with freeze)", () => { const nextState = freeze([ ...baseState.slice(0, MAX * MODIFY_FACTOR).map(todo => freeze({ ...todo, done: true }) ), ...baseState.slice(MAX * MODIFY_FACTOR) ]) })
measure("naive handcrafted reducer (without freeze)", () => { const nextState = baseState.map((todo, index) => { if (index < MAX * MODIFY_FACTOR) return { ...todo, done: true } else return todo }) })
measure("naive handcrafted reducer (with freeze)", () => { const nextState = deepFreeze( baseState.map((todo, index) => { if (index < MAX * MODIFY_FACTOR) return { ...todo, done: true } else return todo }) ) })
measure("immutableJS", () => { let state = immutableJsBaseState state.withMutations(state => { for (let i = 0; i < MAX * MODIFY_FACTOR; i++) { state.setIn([i, "done"], true) } }) })
measure("immer (proxy) - with autofreeze", () => { setAutoFreezeProxy(true) immerProxy(frozenBazeState, draft => { for (let i = 0; i < MAX * MODIFY_FACTOR; i++) { draft[i].done = true } }) measure("immutableJS + toJS", () => { let state = immutableJsBaseState .withMutations(state => { for (let i = 0; i < MAX * MODIFY_FACTOR; i++) { state.setIn([i, "done"], true) } }) .toJS() })
measure("immer (proxy) - without autofreeze", () => { setAutoFreezeProxy(false)4 unmodified lines }) setAutoFreezeProxy(true) })
measure("immer (es5) - with autofreeze", () => { setAutoFreezeEs5(true) immerEs5(frozenBazeState, draft => { measure("immer (proxy) - with autofreeze", () => { setAutoFreezeProxy(true) immerProxy(frozenBazeState, draft => { for (let i = 0; i < MAX * MODIFY_FACTOR; i++) { draft[i].done = true } })7 unmodified lines } }) setAutoFreezeEs5(true) })
measure("immer (es5) - with autofreeze", () => { setAutoFreezeEs5(true) immerEs5(frozenBazeState, draft => { for (let i = 0; i < MAX * MODIFY_FACTOR; i++) { draft[i].done = true } }) })})modified:__tests__/base.js+40 added-9 removed
52 unmodified lines53 // structural sharing?54 expect(nextState.nested).toBe(baseState.nested)55 })56 57- it("deep change bubbles up", () => {58- const nextState = immer(baseState, s => {59- s.anObject.nested.yummie = false57+ if (58+ ("should preserve type",59+ () => {60+ const nextState = immer(baseState, s => {61+ expect(Array.isArray(s)).toBe(true)62+ expect(s.protoType).toBe(Object)63+ s.anArray.push(3)64+ s.aProp = "hello world"65+ expect(Array.isArray(s)).toBe(true)66+ expect(s.protoType).toBe(Object)67+ })68+ expect(Array.isArray(nextState)).toBe(true)69+ expect(nextState.protoType).toBe(Object)70 })71+ )72+ it("deep change bubbles up", () => {73+ const nextState = immer(baseState, s => {74+ s.anObject.nested.yummie = false75+ })61- expect(nextState).not.toBe(baseState)62- expect(nextState.anObject).not.toBe(baseState.anObject)63- expect(baseState.anObject.nested.yummie).toBe(true)64- expect(nextState.anObject.nested.yummie).toBe(false)65- expect(nextState.anArray).toBe(baseState.anArray)66- })76+ expect(nextState).not.toBe(baseState)77+ expect(nextState.anObject).not.toBe(baseState.anObject)78+ expect(baseState.anObject.nested.yummie).toBe(true)79+ expect(nextState.anObject.nested.yummie).toBe(false)80+ expect(nextState.anArray).toBe(baseState.anArray)81+ })82 83 it("can add props", () => {84 const nextState = immer(baseState, s => {85 s.anObject.cookie = {tasty: true}61 unmodified lines147 1148 ])149 })150 151+ it("can delete array items", () => {152+ const nextState = immer(baseState, s => {153+ s.anArray.length = 3154+ })155+ expect(nextState).not.toBe(baseState)156+ expect(nextState.anObject).toBe(baseState.anObject)157+ expect(nextState.anArray).not.toBe(baseState.anArray)158+ expect(nextState.anArray).toEqual([3, 2, {c: 3}])159+ })160+161 it("should support sorting arrays", () => {162 const nextState = immer(baseState, s => {163 s.anArray[2].c = 4164 s.anArray.sort()82 unmodified lines247 s.aProp = "hello"248 delete s.anObject249 obj.coffee = true250 s.messy = obj251+ debugger252 })253 expect(nextState).not.toBe(baseState)254 expect(nextState.anArray).toBe(baseState.anArray)255 expect(enumerableOnly(nextState)).toEqual({99 unmodified lines355 function enumerableOnly(x) {356 // this can be done better...357 return JSON.parse(JSON.stringify(x))358 }359+360+// TODO: test problem scenarios361+// nesting immmer362+// non-trees363+// complex objects / functionsadded:images/immer.pngbinary
A binary file, added.
added:images/performance.pngbinary
A binary file, added.
modified:es5.js+94 added-97 removed
1 "use strict"2 // @ts-check3 4-const PROXY_TARGET = Symbol("immer-proxy")5-const CHANGED_STATE = Symbol("immer-changed-state")6-const PARENT = Symbol("immer-parent")4+const PROXY_STATE = Symbol("immer-proxy-state") // TODO: create per closure, to avoid sharing proxies between multiple immer version5 6 let autoFreeze = true7 8 /**9 unmodified lines18 function immer(baseState, thunk) {19 let finalizing = false20 let finished = false21 const descriptors = {}24- const proxies = []22+ const states = []23 24+ class State {25+ constructor(parent, proxy, base) {26+ this.modified = false27+ this.hasCopy = false28+ this.parent = parent29+ this.base = base30+ this.proxy = proxy31+ this.copy = undefined32+ }33+34+ get source() {35+ return this.hasCopy ? this.copy : this.base36+ }37+38+ get(prop) {39+ assertUnfinished()40+ const value = this.source[prop]41+ if (!finalizing && !isProxy(value) && isProxyable(value)) {42+ this.prepareCopy()43+ return (this.copy[prop] = createProxy(this, value))44+ }45+ return value46+ }47+48+ set(prop, value) {49+ assertUnfinished()50+ if (!this.modified) {51+ if (this.source[prop] === value) return52+ this.markChanged()53+ }54+ this.prepareCopy()55+ this.copy[prop] = value56+ }57+58+ markChanged() {59+ if (!this.modified) {60+ this.modified = true61+ if (this.parent) this.parent.markChanged()62+ }63+ }64+65+ prepareCopy() {66+ if (this.hasCopy) return67+ this.hasCopy = true68+ this.copy = Array.isArray(this.base)69+ ? this.base.slice()70+ : Object.assign({}, this.base)71+ }72+ }73+74 // creates a proxy for plain objects / arrays27- function createProxy(base, parent) {75+ function createProxy(parent, base) {76 let proxy29- if (isPlainObject(base)) proxy = createObjectProxy(base)30- else if (Array.isArray(base)) proxy = createArrayProxy(base)31- else throw new Error("Expected a plain object or array")32- createHiddenProperty(proxy, PROXY_TARGET, base)33- createHiddenProperty(proxy, CHANGED_STATE, false)34- createHiddenProperty(proxy, PARENT, parent)35- proxies.push(proxy)77+ if (Array.isArray(base)) proxy = createArrayProxy(base)78+ else proxy = createObjectProxy(base)79+ const state = new State(parent, proxy, base)80+ createHiddenProperty(proxy, PROXY_STATE, state)81+ states.push(state)82 return proxy83 }84 39- function assertUnfinished() {40- if (finished)41- throw new Error(42- "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process?"43- )44- }45-46- function proxySet(proxy, prop, value) {47- // immer func not ended?48- assertUnfinished()49- // actually a change?50- if (Object.is(proxy[prop], value)) return51- // mark changed52- markDirty(proxy)53- // and stop proxying, we know this object has changed54- Object.defineProperty(proxy, prop, {55- enumerable: true,56- writable: true,57- configurable: true,58- value: value59- })60- }61-85 function createPropertyProxy(prop) {86 return (87 descriptors[prop] ||88 (descriptors[prop] = {89 configurable: true,90 enumerable: true,91 get() {69- assertUnfinished()70- // find the target object71- const target = this[PROXY_TARGET]72- // find the original value73- const value = target[prop]74- // if we are finalizing, don't bother creating proxies, just return base value75- if (finalizing) return value76- // if not proxy-able, return value77- if (!isPlainObject(value) && !Array.isArray(value))78- return value79- // otherwise, create proxy80- const proxy = createProxy(value, this)81- // and make sure this proxy is returned from this prop in the future if read82- // (write behavior as is)83- Object.defineProperty(this, prop, {84- configurable: true,85- enumerable: true,86- get() {87- return proxy88- },89- set(value) {90- proxySet(this, prop, value)91- }92- })93- return proxy92+ return this[PROXY_STATE].get(prop)93 },94 set(value) {96- proxySet(this, prop, value)95+ this[PROXY_STATE].set(prop, value)96 }97 })98 )99 }100 101 function createObjectProxy(base) {103- const proxy = {}102+ const proxy = Object.assign({}, base)103 Object.keys(base).forEach(prop =>104 Object.defineProperty(proxy, prop, createPropertyProxy(prop))105 )106 return proxy107 }108 109 function createArrayProxy(base) {111- const proxy = []110+ const proxy = new Array(base.length)111 for (let i = 0; i < base.length; i++)112 Object.defineProperty(proxy, "" + i, createPropertyProxy("" + i))113 return proxy114 }115 116+ function assertUnfinished() {117+ if (finished)118+ throw new Error(119+ "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process?"120+ )121+ }122+123 // this sounds very expensive, but actually it is not that extensive in practice124 // as it will only visit proxies, and only do key-based change detection for objects for125 // which it is not already know that they are changed (that is, only object for which no known key was changed)126 function markChanges() {127 // intentionally we process the proxies in reverse order;128 // ideally we start by processing leafs in the tree, because if a child has changed, we don't have to check the parent anymore129 // reverse order of proxy creation approximates this124- for (let i = proxies.length - 1; i >= 0; i--) {125- const proxy = proxies[i]126- if (127- proxy[CHANGED_STATE] === false &&128- ((isPlainObject(proxy) && hasObjectChanges(proxy)) ||129- (Array.isArray(proxy) && hasArrayChanges(proxy)))130- ) {131- markDirty(proxy)130+ for (let i = states.length - 1; i >= 0; i--) {131+ const state = states[i]132+ if (state.modified === false) {133+ if (Array.isArray(state.base)) {134+ if (hasArrayChanges(state)) state.markChanged()135+ } else if (hasObjectChanges(state)) state.markChanged()136 }137 }138 }139 136- function hasObjectChanges(proxy) {137- const baseKeys = Object.keys(proxy[PROXY_TARGET])138- const keys = Object.keys(proxy)140+ function hasObjectChanges(state) {141+ const baseKeys = Object.keys(state.base)142+ const keys = Object.keys(state.proxy)143 return !shallowEqual(baseKeys, keys)144 }145 142- function hasArrayChanges(proxy) {143- return proxy[PROXY_TARGET].length !== proxy.length146+ function hasArrayChanges(state) {147+ return state.proxy.length !== state.base.length148 }149 150 function finalize(proxy) {151 // given a base object, returns it if unmodified, or return the changed cloned if modified152 if (!isProxy(proxy)) return proxy149- if (!proxy[CHANGED_STATE]) return proxy[PROXY_TARGET] // return the original target150- if (isPlainObject(proxy)) return finalizeObject(proxy)153+ const state = proxy[PROXY_STATE]154+ if (state.modified === false) return state.base // return the original target155 if (Array.isArray(proxy)) return finalizeArray(proxy)152- throw new Error("Illegal state")156+ return finalizeObject(proxy)157 }158 159 function finalizeObject(proxy) {156- const res = {}157- Object.keys(proxy).forEach(prop => {158- res[prop] = finalize(proxy[prop])160+ const res = Object.assign({}, proxy)161+ Object.keys(res).forEach(prop => {162+ res[prop] = finalize(res[prop])163 })164 return freeze(res)165 }166 1 unmodified line168 return freeze(proxy.map(finalize))169 }170 171 // create proxy for root168- const rootClone = createProxy(baseState, undefined)172+ const rootClone = createProxy(undefined, baseState)173 // execute the thunk174 const maybeVoidReturn = thunk(rootClone)175 //values either than undefined will trigger warning;176 !Object.is(maybeVoidReturn, undefined) &&9 unmodified lines186 finished = true187 return res188 }189 186-function markDirty(proxy) {187- proxy[CHANGED_STATE] = true188- let parent = proxy189- while ((parent = parent[PARENT])) {190- if (parent[CHANGED_STATE] === true) return191- parent[CHANGED_STATE] = true192- }190+function isProxy(value) {191+ return !!value && !!value[PROXY_STATE]192 }193 195-function isPlainObject(value) {196- if (value === null || typeof value !== "object") return false194+function isProxyable(value) {195+ if (!value) return false196+ if (typeof value !== "object") return false197+ if (Array.isArray(value)) return true198 const proto = Object.getPrototypeOf(value)198- return proto === Object.prototype || proto === null199+ return (proto === proto) === null || Object.prototype200 }201 201-function isProxy(value) {202- return !!(value && value[PROXY_TARGET])203-}204-202 function freeze(value) {203 if (autoFreeze) {204 Object.freeze(value)205 }51 unmodified linesmodified:immer.js+158 added-147 removed
4 unmodified lines5 throw new Error(6 "Immer requires `Proxy` to be available, but it seems to be not available on your platform. Consider requiring immer '\"immer/es5\"' instead."7 )8 9-/**10- * @typedef {Object} RevocableProxy11- * @property {any} proxy12- * @property {Function} revoke13- */9+const PROXY_STATE = Symbol("immer-proxy-state") // TODO: create per closure, to avoid sharing proxies between multiple immer version10+let autoFreeze = true11 15-const IMMER_PROXY = Symbol("immer-proxy") // TODO: create per closure, to avoid sharing proxies between multiple immer version12+const objectTraps = {13+ get(target, prop) {14+ if (prop === PROXY_STATE) return target15+ return target.get(prop)16+ },17+ has(target, prop) {18+ return prop in target.source19+ },20+ ownKeys(target) {21+ return Reflect.ownKeys(target.source)22+ },23+ set(target, prop, value) {24+ target.set(prop, value)25+ return true26+ },27+ deleteProperty(target, prop) {28+ target.deleteProp(prop)29+ return true30+ },31+ getOwnPropertyDescriptor(target, prop) {32+ return target.getOwnPropertyDescriptor(prop)33+ },34+ defineProperty(target, property, descriptor) {35+ target.defineProperty(property, descriptor)36+ return true37+ },38+ setPrototypeOf() {39+ throw new Error("Don't even try this...")40+ }41+}42 17-// This property indicates that the current object is cloned for another object,18-// to make sure the proxy of a frozen object is writeable19-const CLONE_TARGET = Symbol("immer-clone-target")43+const arrayTraps = {44+ get(target, prop) {45+ if (prop === PROXY_STATE) return target[0]46+ return target[0].get(prop)47+ },48+ has(target, prop) {49+ return prop in target[0].source50+ },51+ ownKeys(target) {52+ return Reflect.ownKeys(target[0].source)53+ },54+ set(target, prop, value) {55+ target[0].set(prop, value)56+ return true57+ },58+ deleteProperty(target, prop) {59+ target[0].deleteProp(prop)60+ return true61+ },62+ getOwnPropertyDescriptor(target, prop) {63+ return target[0].getOwnPropertyDescriptor(prop)64+ },65+ defineProperty(target, property, descriptor) {66+ target[0].defineProperty(property, descriptor)67+ return true68+ },69+ setPrototypeOf() {70+ throw new Error("Don't even try this...")71+ }72+}73 21-let autoFreeze = true22-74 /**75 * Immer takes a state, and runs a function against it.76 * That function can freely mutate the state, as it will create copies-on-write.77 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned3 unmodified lines81 * @param {Function} thunk - function that receives a proxy of the base state as first argument and which can be freely modified82 * @returns {any} a new state, or the base state if nothing was modified83 */84 function immer(baseState, thunk) {34- /**35- * Maps baseState objects to revocable proxies36- * @type {Map<Object,RevocableProxy>}37- */38- const revocableProxies = new Map()85+ const revocableProxies = []39- // Maps baseState objects to their copies86 41- const copies = new Map()87+ class State {88+ constructor(parent, base) {89+ this.modified = false90+ this.parent = parent91+ this.base = base92+ this.copy = undefined93+ this.proxies = {}94+ }95 43- const objectTraps = {44- get(target, prop) {45- if (prop === IMMER_PROXY) return target46- return createProxy(getCurrentSource(target)[prop])47- },48- has(target, prop) {49- return prop in getCurrentSource(target)50- },51- ownKeys(target) {52- return Reflect.ownKeys(getCurrentSource(target))53- },54- set(target, prop, value) {55- const current = createProxy(getCurrentSource(target)[prop])56- const newValue = createProxy(value)57- if (current !== newValue) {58- const copy = getOrCreateCopy(target)59- copy[prop] = isProxy(newValue)60- ? newValue[IMMER_PROXY]61- : newValue96+ get source() {97+ return this.modified === true ? this.copy : this.base98+ }99+100+ get(prop) {101+ if (this.modified) {102+ const value = this.copy[prop]103+ if (!isProxy(value) && isProxyable(value))104+ return (this.copy[prop] = createProxy(this, value))105+ return value106+ } else {107+ if (prop in this.proxies) return this.proxies[prop]108+ const value = this.base[prop]109+ if (!isProxy(value) && isProxyable(value))110+ return (this.proxies[prop] = createProxy(this, value))111+ return value112 }63- return true64- },65- deleteProperty(target, property) {66- const copy = getOrCreateCopy(target)67- delete copy[property]68- return true69- },70- getOwnPropertyDescriptor(target, prop) {71- return Reflect.getOwnPropertyDescriptor(72- getCurrentSource(target),73- prop74- )75- },76- defineProperty(target, property, descriptor) {77- Object.defineProperty(getOrCreateCopy(target), property, descriptor)78- return true79- },80- setPrototypeOf() {81- throw new Error("Don't even try this...")113 }83- }114 85- // creates a copy for a base object if there ain't one86- function getOrCreateCopy(base) {87- let copy = copies.get(base)88- if (copy) return copy89- const cloneTarget = base[CLONE_TARGET]90- if (cloneTarget) {91- // base is a clone already (source was frozen), no need to create addtional copy92- copies.set(cloneTarget, base)93- return base115+ set(prop, value) {116+ if (!this.modified) {117+ if (118+ (prop in this.base && this.base[prop] === value) ||119+ (prop in this.proxies && this.proxies[prop] === value)120+ )121+ return122+ this.markChanged()123+ }124+ this.copy[prop] = value125 }95- // create a fresh copy96- copy = Array.isArray(base) ? base.slice() : Object.assign({}, base)97- copies.set(base, copy)98- return copy99- }126 101- // returns the current source of truth for a base object102- function getCurrentSource(base) {103- const copy = copies.get(base)104- return copy || base105- }127+ deleteProp(prop) {128+ this.markChanged()129+ delete this.copy[prop]130+ }131 107- // creates a proxy for plain objects / arrays108- function createProxy(base) {109- if (isPlainObject(base) || Array.isArray(base)) {110- if (isProxy(base)) return base // avoid double wrapping111- if (revocableProxies.has(base))112- return revocableProxies.get(base).proxy113- let proxyTarget114- // special case, if the base tree is frozen, we cannot modify it's proxy it in strict mode, clone first.115- if (Object.isFrozen(base)) {116- proxyTarget = Array.isArray(base)117- ? base.slice()118- : Object.assign({}, base)119- Object.defineProperty(proxyTarget, CLONE_TARGET, {120- enumerable: false,121- value: base,122- configurable: true123- })124- } else {125- proxyTarget = base132+ getOwnPropertyDescriptor(prop) {133+ const owner = this.modified134+ ? this.copy135+ : prop in this.proxies ? this.proxies : this.base136+ const descriptor = Reflect.getOwnPropertyDescriptor(owner, prop)137+ if (descriptor) descriptor.configurable = true // XXX: is this really needed?138+ return descriptor139+ }140+141+ defineProperty(property, descriptor) {142+ this.markChanged()143+ Object.defineProperty(this.copy, property, descriptor)144+ }145+146+ markChanged() {147+ if (!this.modified) {148+ this.modified = true149+ this.copy = Array.isArray(this.base) // TODO: eliminate those isArray checks?150+ ? this.base.slice()151+ : Object.assign({}, this.base)152+ Object.assign(this.copy, this.proxies) // yup that works for arrays as well153+ if (this.parent) this.parent.markChanged()154 }127- // create the proxy128- const revocableProxy = Proxy.revocable(proxyTarget, objectTraps)129- revocableProxies.set(base, revocableProxy)130- return revocableProxy.proxy155 }132- return base156 }157 135- // checks if the given base object has modifications, either because it is modified, or136- // because one of it's children is137- function hasChanges(base) {138- const proxy = revocableProxies.get(base)139- if (!proxy) return false // nobody did read this object140- if (copies.has(base)) return true // a copy was created, so there are changes141- // look deeper142- const keys = Object.keys(base)143- for (let i = 0; i < keys.length; i++) {144- const value = base[keys[i]]145- if (146- (Array.isArray(value) || isPlainObject(value)) &&147- hasChanges(value)148- )149- return true158+ // creates a proxy for plain objects / arrays159+ function createProxy(parentState, base) {160+ const state = new State(parentState, base)161+ let proxy162+ if (Array.isArray(base)) {163+ // Proxy should be created with an array to make it an array for JS164+ // so... here you have it!165+ proxy = Proxy.revocable([state], arrayTraps)166+ } else {167+ proxy = Proxy.revocable(state, objectTraps)168 }151- return false169+ revocableProxies.push(proxy)170+ return proxy.proxy171 }172 173 // given a base object, returns it if unmodified, or return the changed cloned if modified174 function finalize(base) {156- if (isPlainObject(base)) return finalizeObject(base)157- if (Array.isArray(base)) return finalizeArray(base)175+ if (isProxy(base)) {176+ const state = base[PROXY_STATE]177+ if (state.modified === true) {178+ if (Array.isArray(state.base)) return finalizeArray(state)179+ return finalizeObject(state)180+ } else return state.base181+ }182 return base183 }184 161- function finalizeObject(thing) {162- if (!hasChanges(thing)) return thing163- const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..185+ function finalizeObject(state) {186+ const copy = state.copy187 Object.keys(copy).forEach(prop => {188 copy[prop] = finalize(copy[prop])189 })167- delete copy[CLONE_TARGET]190 return freeze(copy)191 }192 171- function finalizeArray(thing) {172- if (!hasChanges(thing)) return thing173- const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..193+ function finalizeArray(state) {194+ const copy = state.copy195 copy.forEach((value, index) => {196 copy[index] = finalize(copy[index])197 })177- delete copy[CLONE_TARGET]198 return freeze(copy)199 }200 201 // create proxy for root182- const rootClone = createProxy(baseState)202+ const rootClone = createProxy(undefined, baseState)203 // execute the thunk204 const maybeVoidReturn = thunk(rootClone)205 //values either than undefined will trigger warning;206 !Object.is(maybeVoidReturn, undefined) &&207 console.warn(208 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`209 )190- // console.log(`proxies: ${revocableProxies.size}, copies: ${copies.size}`)191- // revoke all proxies192- revoke(revocableProxies)210 // and finalize the modified proxy194- return finalize(baseState)211+ const res = finalize(rootClone)212+ // revoke all proxies213+ revocableProxies.forEach(p => p.revoke())214+ return res215 }216 197-/**198- * Revoke all the proxies stored in the revocableProxies map199- *200- * @param {Map<Object,RevocableProxy>} revocableProxies201- */202-function revoke(revocableProxies) {203- for (var revocableProxy of revocableProxies.values()) {204- revocableProxy.revoke()205- }217+function isProxy(value) {218+ return !!value && !!value[PROXY_STATE]219 }220 208-function isPlainObject(value) {209- if (value === null || typeof value !== "object") return false221+function isProxyable(value) {222+ if (!value) return false223+ if (typeof value !== "object") return false224+ if (Array.isArray(value)) return true225 const proto = Object.getPrototypeOf(value)211- return proto === Object.prototype || proto === null226+ return (proto === proto) === null || Object.prototype227 }228 214-function isProxy(value) {215- return !!value && !!value[IMMER_PROXY]216-}217-229 function freeze(value) {230 if (autoFreeze) {231 Object.freeze(value)232 }20 unmodified linesdeleted:immer.pngbinary
A binary file, deleted.
modified:package.json+1 added-1 removed
5 unmodified lines6 "types": "./index.d.ts",7 "scripts": {8 "test": "jest",9 "test:perf": "node --expose-gc node_modules/jest-cli/bin/jest.js --verbose --testRegex '__performance_tests__/.*'",10- "prettier": "prettier \"*/**/*.js\" --ignore-path ./.prettierignore --write && git add . && git status"10+ "prettier": "prettier \"*/**/*.js\" --ignore-path ./.prettierignore --write"11 },12 "pre-commit": [13 "prettier"14 ],40 unmodified linesmodified:readme.md+20 added-28 removed
9 unmodified lines10 The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_.11 Once all your mutations are completed, immer will produce the _nextState_ based on the mutations to the draft state.12 This means that you can interact with your data by simply modifying it, while keeping all the benefits of immutable data.13 14-14+15 16 Using immer is like having a personal assistant; he takes a letter (the current state), and gives you a copy (draft) to jot changes onto. Once you are done, the assistant will take your draft and produce the real immutable, final letter for you (the next state).17 18 A mindful reader might notice that this is quite similar to `withMutations` of ImmutableJS. It is indeed, but generalized and applicable to plain, native JavaScript data structures (arrays and objects) without further needing any library.213 unmodified lines232 })233 }234 ```235 236-## Performance237-238-Here is a [simple benchmark](__tests__/performance.js) on the performance of `immer`.239-This test takes 100.000 todo items, and updates 10.000 of them.240-These tests were executed on Node 8.4.0.241-242-Use `yarn test:perf` to reproduce them locally243-244-```245- ✓ just mutate (3ms)246- (No immutability at all)247- ✓ deepclone, then mutate (409ms)248- (Clone entire tree, then mutate (no structural sharing!))249- ✓ handcrafted reducer (17ms)250- (Implement it as typical Redux reducer, with slices and spread operator)251- ✓ immutableJS (60ms)252- (Use immutableJS and leverage `withMutations` for best performance)253- ✓ immer (proxy) - with autofreeze (305ms)254- (Immer, with auto freeze enabled, default implementation)255- ✓ immer (proxy) - without autofreeze (149ms)256- (Immer, with auto freeze disabled, default implementation)257- ✓ immer (es5) - with autofreeze (436ms)258- (Immer, with auto freeze enabled, compatibility implementation)259- ✓ immer (es5) - without autofreeze (336ms)260- (Immer, with auto freeze disabled, default implementation)261-```262-236 ## Limitations237 238 * Currently, only tree shaped states are supported. Cycles could potentially be supported as well (PR's welcome)239 * Currently, only supports plain objects and arrays. Non-plain data structures (like `Map`, `Set`) not (yet). (PR's welcome)2 unmodified lines242 243 * Make sure to modify the draft state you get passed in in the callback function, not the original current state that was passed as the first argument to `immer`!244 * Since immer uses proxies, reading huge amounts of data from state comes with an overhead. If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the `immer` block or read from the `currentState` rather than the `draftState`245 246+## Performance247+248+Here is a [simple benchmark](__tests__/performance.js) on the performance of `immer`.249+This test takes 100.000 todo items, and updates 10.000 of them.250+_Freeze_ indicates that the state tree has been frozen after producing it. This is a _development_ best practice, as it prevents developers from accidentally modifying the state tree.251+252+These tests were executed on Node 8.4.0.253+Use `yarn test:perf` to reproduce them locally.254+255+256+257+Some observations:258+* The _mutate_, and _deepclone, mutate_ benchmarks establish a baseline on how expensive changing the data is, without immutability (or structural sharing in the deep clone case).259+* The _reducure_ and _naive reducer_ are implemented in typical Redux style reducers. The "smart" implementation slices the collection first, and then maps and freezes only the relevant todos. The "naive" implementation just maps over and processes the entire collection.260+* Immer with proxies is roughly speaking twice as slow as a hand written reducer. This is in practice negclectable.261+* Immer is roughly as fast as ImmutableJS. However, the _immutableJS + toJS_ makes clear the cost that often needs to be paid later; converting the immutableJS objects back to plain objects, to be able to pass them to components, over the network etc... (And there is also the upfront cost of converting data received from e.g. the server to immutable JS)262+* The ES5 implentation of immer is significantly slower. For most reducers this won't matter, but reducers that process large amounts of data might benefit from not (or only partially) using an immer producer. Luckily, immer is fully opt-in.263+* The peeks in the _frozen_ versions of _just mutate_, _deepclone_ and _naive reducer_ come from the fact that they recursively freeze the full state tree, while the other test cases only freeze the modified parts of the tree.264+265 ## Credits266 267 Special thanks goes to @Mendix, which supports it's employees to experiment completely freely two full days a month, which formed the kick-start for this project.