Skip to content
Myr

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)

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

* Intercept array methods to skip proxy creation for perf * Add allReassigned flag * Improve isArrayIndex * Drop dead test * Move array methods to a new plugin * Run additional base tests with array method plugin enabled * Add immutability-profiling script * Update benchmarks to use enableArrayMethods * Add additional array method tests * Document array method internal behaviors * Update import size values * Update import size command * Add array plugin docs

authored by Mark Erikson · committed by GitHub · parent 99e59a8 · Browse files · 20 files+2121 added−53 removed
This commit

State

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

Diff stats

20 files+2121 added−53 removed

  • tests:+751 added−36 removed
  • other:+1370 added−17 removed

20 files+2121 added−53 removed

modified:__tests__/__prod_snapshots__/base.js.snap+63 added-16 removed
1// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html23exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > map drafts > revokes map proxies 1`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;45exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > map drafts > revokes map proxies 2`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;67exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > recipe functions > cannot return a modified child draft 1`] = `[Error: [Immer] minified error nr: 4. Full error at: https://bit.ly/3cXEKWf]`;89exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > set drafts > revokes sets 1`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;1011exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > set drafts > revokes sets 2`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;1213exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > throws when Object.defineProperty() is used on drafts 1`] = `[Error: [Immer] minified error nr: 11. Full error at: https://bit.ly/3cXEKWf]`;1415exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > throws when Object.setPrototypeOf() is used on a draft 1`] = `[Error: [Immer] minified error nr: 12. Full error at: https://bit.ly/3cXEKWf]`;1617exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > throws when the draft is modified and another object is returned 1`] = `[Error: [Immer] minified error nr: 4. Full error at: https://bit.ly/3cXEKWf]`;1819exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=false > map drafts > revokes map proxies 1`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;2021exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=false > map drafts > revokes map proxies 2`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;2223exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=false > recipe functions > cannot return a modified child draft 1`] = `[Error: [Immer] minified error nr: 4. Full error at: https://bit.ly/3cXEKWf]`;249exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=false > recipe functions > cannot return an object that references itself 1`] = `[RangeError: Maximum call stack size exceeded]`;1025exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=false > set drafts > revokes sets 1`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;2627exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=false > set drafts > revokes sets 2`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;28
8 unmodified lines
37exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=true > map drafts > revokes map proxies 2`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;3839exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=true > recipe functions > cannot return a modified child draft 1`] = `[Error: [Immer] minified error nr: 4. Full error at: https://bit.ly/3cXEKWf]`;4027exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=true > recipe functions > cannot return an object that references itself 1`] = `[RangeError: Maximum call stack size exceeded]`;2841exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=true > set drafts > revokes sets 1`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;4243exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=true > set drafts > revokes sets 2`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;44
8 unmodified lines
53exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=false > map drafts > revokes map proxies 2`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;5455exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=false > recipe functions > cannot return a modified child draft 1`] = `[Error: [Immer] minified error nr: 4. Full error at: https://bit.ly/3cXEKWf]`;5645exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=false > recipe functions > cannot return an object that references itself 1`] = `[RangeError: Maximum call stack size exceeded]`;4657exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=false > set drafts > revokes sets 1`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;5859exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=false > set drafts > revokes sets 2`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;60
8 unmodified lines
69exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=true > map drafts > revokes map proxies 2`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;7071exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=true > recipe functions > cannot return a modified child draft 1`] = `[Error: [Immer] minified error nr: 4. Full error at: https://bit.ly/3cXEKWf]`;7263exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=true > recipe functions > cannot return an object that references itself 1`] = `[RangeError: Maximum call stack size exceeded]`;6473exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=true > set drafts > revokes sets 1`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;7475exports[`base functionality - auto-freeze=false:shallow-copy=true:use-listener=true > set drafts > revokes sets 2`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;76
8 unmodified lines
85exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=false > map drafts > revokes map proxies 2`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;8687exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=false > recipe functions > cannot return a modified child draft 1`] = `[Error: [Immer] minified error nr: 4. Full error at: https://bit.ly/3cXEKWf]`;8881exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=false > recipe functions > cannot return an object that references itself 1`] = `[RangeError: Maximum call stack size exceeded]`;8289exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=false > set drafts > revokes sets 1`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;9091exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=false > set drafts > revokes sets 2`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;92
8 unmodified lines
101exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=true > map drafts > revokes map proxies 2`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;102103exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=true > recipe functions > cannot return a modified child draft 1`] = `[Error: [Immer] minified error nr: 4. Full error at: https://bit.ly/3cXEKWf]`;10499exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=true > recipe functions > cannot return an object that references itself 1`] = `[RangeError: Maximum call stack size exceeded]`;100105exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=true > set drafts > revokes sets 1`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;106107exports[`base functionality - auto-freeze=true:shallow-copy=false:use-listener=true > set drafts > revokes sets 2`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;108
8 unmodified lines
117exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=false > map drafts > revokes map proxies 2`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;118119exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=false > recipe functions > cannot return a modified child draft 1`] = `[Error: [Immer] minified error nr: 4. Full error at: https://bit.ly/3cXEKWf]`;120117exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=false > recipe functions > cannot return an object that references itself 1`] = `[RangeError: Maximum call stack size exceeded]`;118121exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=false > set drafts > revokes sets 1`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;122123exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=false > set drafts > revokes sets 2`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;124
8 unmodified lines
133exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=true > map drafts > revokes map proxies 2`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;134135exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=true > recipe functions > cannot return a modified child draft 1`] = `[Error: [Immer] minified error nr: 4. Full error at: https://bit.ly/3cXEKWf]`;136135exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=true > recipe functions > cannot return an object that references itself 1`] = `[RangeError: Maximum call stack size exceeded]`;136137exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=true > set drafts > revokes sets 1`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;138139exports[`base functionality - auto-freeze=true:shallow-copy=true:use-listener=true > set drafts > revokes sets 2`] = `[Error: [Immer] minified error nr: 3. Full error at: https://bit.ly/3cXEKWf]`;140
377 unmodified lines
518 },519 },520]521`;522523exports[`complex nesting map / set / object > modify deep object 17`] = `524{525 "map": Map {526 "set1" => Set {527 {528 "a": 2,529 },530 {531 "b": 2,532 },533 },534 "set2" => Set {535 {536 "c": 3,537 },538 },539 },540}541`;542543exports[`complex nesting map / set / object > modify deep object 18`] = `544[545 {546 "op": "remove",547 "path": [548 "map",549 "set1",550 0,551 ],552 "value": {553 "a": 1,554 },555 },556 {557 "op": "add",558 "path": [559 "map",560 "set1",561 0,562 ],563 "value": {564 "a": 2,565 },566 },567]568`;
modified:__tests__/__snapshots__/base.js.snap+83 added
1// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html23exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > array drafts > throws when a non-numeric property is added 1`] = `[Error: [Immer] Immer only supports setting array indices and the 'length' property]`;45exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > array drafts > throws when a non-numeric property is deleted 1`] = `[Error: [Immer] Immer only supports deleting array indices]`;67exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > map drafts > revokes map proxies 1`] = `[Error: [Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}]`;89exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > map drafts > revokes map proxies 2`] = `[Error: [Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}]`;1011exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > recipe functions > cannot return a modified child draft 1`] = `[Error: [Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.]`;1213exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > revokes the draft once produce returns 1`] = `[TypeError: Cannot perform 'get' on a proxy that has been revoked]`;1415exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > revokes the draft once produce returns 2`] = `[TypeError: Cannot perform 'set' on a proxy that has been revoked]`;1617exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > revokes the draft once produce returns 3`] = `[TypeError: Cannot perform 'get' on a proxy that has been revoked]`;1819exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > revokes the draft once produce returns 4`] = `[TypeError: Cannot perform 'set' on a proxy that has been revoked]`;2021exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > revokes the draft once produce returns 5`] = `[TypeError: Cannot perform 'get' on a proxy that has been revoked]`;2223exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > revokes the draft once produce returns 6`] = `[TypeError: Cannot perform 'set' on a proxy that has been revoked]`;2425exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > revokes the draft once produce returns 7`] = `[TypeError: Cannot perform 'get' on a proxy that has been revoked]`;2627exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > revokes the draft once produce returns 8`] = `[TypeError: Cannot perform 'set' on a proxy that has been revoked]`;2829exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > set drafts > revokes sets 1`] = `[Error: [Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}]`;3031exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > set drafts > revokes sets 2`] = `[Error: [Immer] Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {}]`;3233exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > throws when Object.defineProperty() is used on drafts 1`] = `[Error: [Immer] Object.defineProperty() cannot be used on an Immer draft]`;3435exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > throws when Object.setPrototypeOf() is used on a draft 1`] = `[Error: [Immer] Object.setPrototypeOf() cannot be used on an Immer draft]`;3637exports[`base functionality - array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false > throws when the draft is modified and another object is returned 1`] = `[Error: [Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.]`;3839exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=false > array drafts > throws when a non-numeric property is added 1`] = `[Error: [Immer] Immer only supports setting array indices and the 'length' property]`;4041exports[`base functionality - auto-freeze=false:shallow-copy=false:use-listener=false > array drafts > throws when a non-numeric property is deleted 1`] = `[Error: [Immer] Immer only supports deleting array indices]`;42
655 unmodified lines
698 },699 },700]701`;702703exports[`complex nesting map / set / object > modify deep object 17`] = `704{705 "map": Map {706 "set1" => Set {707 {708 "a": 2,709 },710 {711 "b": 2,712 },713 },714 "set2" => Set {715 {716 "c": 3,717 },718 },719 },720}721`;722723exports[`complex nesting map / set / object > modify deep object 18`] = `724[725 {726 "op": "remove",727 "path": [728 "map",729 "set1",730 0,731 ],732 "value": {733 "a": 1,734 },735 },736 {737 "op": "add",738 "path": [739 "map",740 "set1",741 0,742 ],743 "value": {744 "a": 2,745 },746 },747]748`;
modified:__tests__/base.js+605 added-20 removed
5 unmodified lines
6 original,7 isDraft,8 immerable,9 enablePatches,10 enableMapSet10 enableMapSet,11 enableArrayMethods12} from "../src/immer"12import {each, shallowCopy, DRAFT_STATE} from "../src/internal"1314import {15 each,16 shallowCopy,17 DRAFT_STATE,18 clearPlugin,19 PluginArrayMethods20} from "../src/internal"21import deepFreeze from "deep-freeze"22import * as lodash from "lodash"2324enablePatches()
19 unmodified lines
44 }45 }46}4748// Run one additional test suite with the array methods plugin enabled,49// as that should be a separate concern from the other settings50const testArrayMethodsName = `array-plugin=true:auto-freeze=true:shallow-copy=false:use-listener=false`51runBaseTest(testArrayMethodsName, true, false, false, true)5253class Foo {}5442function runBaseTest(name, autoFreeze, useStrictShallowCopy, useListener) {55function runBaseTest(56 name,57 autoFreeze,58 useStrictShallowCopy,59 useListener,60 useArrayMethods = false61) {62 const listener = useListener ? function() {} : undefined6364 const {produce, produceWithPatches} = createPatchedImmer({65 autoFreeze,66 useStrictShallowCopy67 })
18 unmodified lines
86 let origBaseState8788 beforeEach(() => {89 origBaseState = baseState = createBaseState()9091 // Allow running our tests with and without the array method plugin92 if (useArrayMethods) {93 enableArrayMethods()94 } else {95 clearPlugin(PluginArrayMethods)96 }97 })9899 it("returns the original state when no changes are made", () => {100 const nextState = produce(baseState, s => {
626 unmodified lines
727 expect(sum).toBe(120) // 30 + 40 + 50728 })729 expect(result).toBe(base) // No modifications730 })731732 test("mutating item in filter result updates original value", () => {733 const initialState = {734 largeArray: Array.from({length: 10}).map((_, i) => ({735 id: i,736 value: i * 10737 }))738 }739740 const result = produce(initialState, draft => {741 const filtered = draft.largeArray.filter(item => item.id <= 5)742743 filtered[0].value = 999744 draft.filtered = filtered745 })746747 expect(result.largeArray[0].value).toBe(999)748 expect(result.filtered[0].value).toBe(999)749 expect(result.largeArray[0]).toBe(result.filtered[0])750 })751 })752753 describe("map()", () => {754 test("returns new array with mapped items", () => {
428 unmodified lines
1183 expect(result).toBe(base)1184 })1185 })11861187 describe("concat()", () => {1188 test("returns new array with concatenated items", () => {1189 const base = {items: [{id: 1}, {id: 2}]}1190 const result = produce(base, draft => {1191 const concatenated = draft.items.concat([{id: 3}])1192 expect(concatenated).toHaveLength(3)1193 expect(concatenated[2].id).toBe(3)1194 })1195 expect(result).toBe(base)1196 })11971198 test("concat with no arguments creates shallow copy", () => {1199 const base = {1200 items: [1201 {id: 1, value: 10},1202 {id: 2, value: 20}1203 ]1204 }1205 const result = produce(base, draft => {1206 const copy = draft.items.concat()1207 expect(copy).toHaveLength(2)1208 expect(copy[0].id).toBe(1)1209 })1210 expect(result).toBe(base)1211 })12121213 // Behavior differs based on array methods plugin1214 if (useArrayMethods) {1215 test("concat returns base values, not drafts (with plugin)", () => {1216 const base = {items: [{id: 1, value: 10}]}1217 const result = produce(base, draft => {1218 const concatenated = draft.items.concat()1219 // With plugin: concat returns base values, not drafts1220 expect(isDraft(concatenated[0])).toBe(false)1221 })1222 expect(result).toBe(base)1223 })1224 } else {1225 test("concat returns draft proxies (default behavior)", () => {1226 const base = {items: [{id: 1, value: 10}]}1227 const result = produce(base, draft => {1228 const concatenated = draft.items.concat()1229 // Without plugin: concat returns draft proxies via get trap1230 expect(isDraft(concatenated[0])).toBe(true)1231 })1232 expect(result).toBe(base)1233 })1234 }12351236 test("concat with multiple arrays", () => {1237 const base = {items: [{id: 1}]}1238 const result = produce(base, draft => {1239 const concatenated = draft.items.concat([{id: 2}], [{id: 3}])1240 expect(concatenated).toHaveLength(3)1241 expect(concatenated[1].id).toBe(2)1242 expect(concatenated[2].id).toBe(3)1243 })1244 expect(result).toBe(base)1245 })12461247 test("concat result assigned to draft works", () => {1248 const base = {items: [{id: 1}], combined: []}1249 const result = produce(base, draft => {1250 draft.combined = draft.items.concat([{id: 2}])1251 })1252 expect(result.combined).toHaveLength(2)1253 expect(result.combined[0].id).toBe(1)1254 expect(result.combined[1].id).toBe(2)1255 })12561257 test("concat with primitives", () => {1258 const base = {numbers: [1, 2, 3]}1259 const result = produce(base, draft => {1260 const concatenated = draft.numbers.concat([4, 5])1261 expect(concatenated).toEqual([1, 2, 3, 4, 5])1262 })1263 expect(result).toBe(base)1264 })1265 })12661267 describe("flat()", () => {1268 test("returns flattened array", () => {1269 const base = {1270 nested: [1271 [1, 2],1272 [3, 4]1273 ]1274 }1275 const result = produce(base, draft => {1276 const flattened = draft.nested.flat()1277 expect(flattened).toEqual([1, 2, 3, 4])1278 })1279 expect(result).toBe(base)1280 })12811282 test("flat with depth parameter", () => {1283 const base = {nested: [[[1, 2]], [[3, 4]]]}1284 const result = produce(base, draft => {1285 const shallow = draft.nested.flat(1)1286 expect(shallow).toEqual([1287 [1, 2],1288 [3, 4]1289 ])1290 const deep = draft.nested.flat(2)1291 expect(deep).toEqual([1, 2, 3, 4])1292 })1293 expect(result).toBe(base)1294 })12951296 // Behavior differs based on array methods plugin1297 if (useArrayMethods) {1298 test("flat returns base values, not drafts (with plugin)", () => {1299 const base = {nested: [[{id: 1}], [{id: 2}]]}1300 const result = produce(base, draft => {1301 const flattened = draft.nested.flat()1302 expect(flattened).toHaveLength(2)1303 // With plugin: flat returns base values, not drafts1304 expect(isDraft(flattened[0])).toBe(false)1305 })1306 expect(result).toBe(base)1307 })1308 } else {1309 test("flat returns draft proxies (default behavior)", () => {1310 const base = {nested: [[{id: 1}], [{id: 2}]]}1311 const result = produce(base, draft => {1312 const flattened = draft.nested.flat()1313 expect(flattened).toHaveLength(2)1314 // Without plugin: flat returns draft proxies via get trap1315 expect(isDraft(flattened[0])).toBe(true)1316 })1317 expect(result).toBe(base)1318 })1319 }13201321 test("flat with empty nested arrays", () => {1322 const base = {nested: [[], [1, 2], []]}1323 const result = produce(base, draft => {1324 const flattened = draft.nested.flat()1325 expect(flattened).toEqual([1, 2])1326 })1327 expect(result).toBe(base)1328 })13291330 test("flat result assigned to draft works", () => {1331 const base = {nested: [[1], [2]], result: []}1332 const result = produce(base, draft => {1333 draft.result = draft.nested.flat()1334 })1335 expect(result.result).toEqual([1, 2])1336 })1337 })13381339 describe("findIndex()", () => {1340 test("returns index of found item", () => {1341 const base = createTestData()1342 const result = produce(base, draft => {1343 const index = draft.items.findIndex(item => item.id === 3)1344 expect(index).toBe(2)1345 })1346 expect(result).toBe(base)1347 })13481349 test("returns -1 when not found", () => {1350 const base = createTestData()1351 const result = produce(base, draft => {1352 const index = draft.items.findIndex(item => item.id === 999)1353 expect(index).toBe(-1)1354 })1355 expect(result).toBe(base)1356 })13571358 test("predicate receives correct arguments", () => {1359 const base = createTestData()1360 const result = produce(base, draft => {1361 draft.items.findIndex((item, index, array) => {1362 expect(typeof index).toBe("number")1363 expect(Array.isArray(array)).toBe(true)1364 return false1365 })1366 })1367 expect(result).toBe(base)1368 })13691370 test("works with primitives", () => {1371 const base = {numbers: [10, 20, 30, 40, 50]}1372 const result = produce(base, draft => {1373 const index = draft.numbers.findIndex(n => n > 25)1374 expect(index).toBe(2)1375 })1376 expect(result).toBe(base)1377 })1378 })13791380 describe("findLastIndex()", () => {1381 test("returns last matching index", () => {1382 const base = {1383 items: [1384 {id: 1, type: "A"},1385 {id: 2, type: "B"},1386 {id: 3, type: "A"}1387 ]1388 }1389 const result = produce(base, draft => {1390 const index = draft.items.findLastIndex(item => item.type === "A")1391 expect(index).toBe(2)1392 })1393 expect(result).toBe(base)1394 })13951396 test("returns -1 when not found", () => {1397 const base = {items: [{id: 1}, {id: 2}]}1398 const result = produce(base, draft => {1399 const index = draft.items.findLastIndex(item => item.id === 999)1400 expect(index).toBe(-1)1401 })1402 expect(result).toBe(base)1403 })14041405 test("predicate receives correct arguments", () => {1406 const base = createTestData()1407 const result = produce(base, draft => {1408 draft.items.findLastIndex((item, index, array) => {1409 expect(typeof index).toBe("number")1410 expect(Array.isArray(array)).toBe(true)1411 return false1412 })1413 })1414 expect(result).toBe(base)1415 })1416 })14171418 describe("some()", () => {1419 test("returns true when condition met", () => {1420 const base = createTestData()1421 const result = produce(base, draft => {1422 const hasHighValue = draft.items.some(item => item.value > 40)1423 expect(hasHighValue).toBe(true)1424 })1425 expect(result).toBe(base)1426 })14271428 test("returns false when no items match", () => {1429 const base = createTestData()1430 const result = produce(base, draft => {1431 const hasHugeValue = draft.items.some(item => item.value > 1000)1432 expect(hasHugeValue).toBe(false)1433 })1434 expect(result).toBe(base)1435 })14361437 test("short-circuits on first match", () => {1438 const base = {items: [{id: 1}, {id: 2}, {id: 3}]}1439 let callCount = 01440 const result = produce(base, draft => {1441 const found = draft.items.some(item => {1442 callCount++1443 return item.id === 11444 })1445 expect(found).toBe(true)1446 })1447 expect(callCount).toBe(1)1448 expect(result).toBe(base)1449 })14501451 test("predicate receives correct arguments", () => {1452 const base = createTestData()1453 const result = produce(base, draft => {1454 draft.items.some((item, index, array) => {1455 expect(typeof index).toBe("number")1456 expect(Array.isArray(array)).toBe(true)1457 return false1458 })1459 })1460 expect(result).toBe(base)1461 })14621463 test("works with primitives", () => {1464 const base = {numbers: [1, 2, 3, 4, 5]}1465 const result = produce(base, draft => {1466 expect(draft.numbers.some(n => n > 3)).toBe(true)1467 expect(draft.numbers.some(n => n > 10)).toBe(false)1468 })1469 expect(result).toBe(base)1470 })1471 })14721473 describe("every()", () => {1474 test("returns true when all items match", () => {1475 const base = createTestData()1476 const result = produce(base, draft => {1477 const allPositive = draft.items.every(item => item.value > 0)1478 expect(allPositive).toBe(true)1479 })1480 expect(result).toBe(base)1481 })14821483 test("returns false when any item fails", () => {1484 const base = createTestData()1485 const result = produce(base, draft => {1486 const allHighValue = draft.items.every(item => item.value > 30)1487 expect(allHighValue).toBe(false)1488 })1489 expect(result).toBe(base)1490 })14911492 test("short-circuits on first failure", () => {1493 const base = {items: [{id: 1}, {id: 2}, {id: 3}]}1494 let callCount = 01495 const result = produce(base, draft => {1496 const allMatch = draft.items.every(item => {1497 callCount++1498 return item.id === 9991499 })1500 expect(allMatch).toBe(false)1501 })1502 expect(callCount).toBe(1)1503 expect(result).toBe(base)1504 })15051506 test("predicate receives correct arguments", () => {1507 const base = createTestData()1508 const result = produce(base, draft => {1509 draft.items.every((item, index, array) => {1510 expect(typeof index).toBe("number")1511 expect(Array.isArray(array)).toBe(true)1512 return true1513 })1514 })1515 expect(result).toBe(base)1516 })15171518 test("returns true for empty array", () => {1519 const base = {items: []}1520 const result = produce(base, draft => {1521 const allMatch = draft.items.every(() => false)1522 expect(allMatch).toBe(true)1523 })1524 expect(result).toBe(base)1525 })1526 })15271528 describe("lastIndexOf()", () => {1529 test("returns last index of item", () => {1530 const base = {items: [1, 2, 3, 2, 1]}1531 const result = produce(base, draft => {1532 const index = draft.items.lastIndexOf(2)1533 expect(index).toBe(3)1534 })1535 expect(result).toBe(base)1536 })15371538 test("returns -1 when not found", () => {1539 const base = {items: [1, 2, 3]}1540 const result = produce(base, draft => {1541 const index = draft.items.lastIndexOf(99)1542 expect(index).toBe(-1)1543 })1544 expect(result).toBe(base)1545 })15461547 test("works with fromIndex parameter", () => {1548 const base = {items: [1, 2, 3, 2, 1]}1549 const result = produce(base, draft => {1550 const index = draft.items.lastIndexOf(2, 2)1551 expect(index).toBe(1)1552 })1553 expect(result).toBe(base)1554 })15551556 test("works with negative fromIndex", () => {1557 const base = {items: [1, 2, 3, 2, 1]}1558 const result = produce(base, draft => {1559 const index = draft.items.lastIndexOf(2, -2)1560 expect(index).toBe(3)1561 })1562 expect(result).toBe(base)1563 })1564 })15651566 describe("includes()", () => {1567 test("returns true when item exists", () => {1568 const base = {items: [1, 2, 3, 4, 5]}1569 const result = produce(base, draft => {1570 expect(draft.items.includes(3)).toBe(true)1571 })1572 expect(result).toBe(base)1573 })15741575 test("returns false when item doesn't exist", () => {1576 const base = {items: [1, 2, 3, 4, 5]}1577 const result = produce(base, draft => {1578 expect(draft.items.includes(99)).toBe(false)1579 })1580 expect(result).toBe(base)1581 })15821583 test("works with fromIndex parameter", () => {1584 const base = {items: [1, 2, 3, 4, 5]}1585 const result = produce(base, draft => {1586 expect(draft.items.includes(2, 2)).toBe(false)1587 expect(draft.items.includes(3, 2)).toBe(true)1588 })1589 expect(result).toBe(base)1590 })15911592 test("works with NaN", () => {1593 const base = {items: [1, NaN, 3]}1594 const result = produce(base, draft => {1595 expect(draft.items.includes(NaN)).toBe(true)1596 })1597 expect(result).toBe(base)1598 })15991600 test("works with negative fromIndex", () => {1601 const base = {items: [1, 2, 3, 4, 5]}1602 const result = produce(base, draft => {1603 expect(draft.items.includes(4, -2)).toBe(true)1604 expect(draft.items.includes(2, -2)).toBe(false)1605 })1606 expect(result).toBe(base)1607 })1608 })16091610 describe("toString()", () => {1611 test("returns string representation", () => {1612 const base = {items: [1, 2, 3]}1613 const result = produce(base, draft => {1614 const str = draft.items.toString()1615 expect(str).toBe("1,2,3")1616 })1617 expect(result).toBe(base)1618 })16191620 test("works with objects", () => {1621 const base = {items: [{id: 1}, {id: 2}]}1622 const result = produce(base, draft => {1623 const str = draft.items.toString()1624 expect(str).toContain("[object Object]")1625 })1626 expect(result).toBe(base)1627 })16281629 test("works with empty array", () => {1630 const base = {items: []}1631 const result = produce(base, draft => {1632 const str = draft.items.toString()1633 expect(str).toBe("")1634 })1635 expect(result).toBe(base)1636 })1637 })16381639 describe("toLocaleString()", () => {1640 test("returns locale string representation", () => {1641 const base = {items: [1, 2, 3]}1642 const result = produce(base, draft => {1643 const str = draft.items.toLocaleString()1644 expect(typeof str).toBe("string")1645 })1646 expect(result).toBe(base)1647 })16481649 test("works with numbers", () => {1650 const base = {numbers: [1000, 2000]}1651 const result = produce(base, draft => {1652 const str = draft.numbers.toLocaleString()1653 expect(typeof str).toBe("string")1654 })1655 expect(result).toBe(base)1656 })1657 })16581659 describe("findLast() additional edge cases", () => {1660 test("returns undefined when not found", () => {1661 const base = {items: [{id: 1}, {id: 2}, {id: 3}]}1662 const result = produce(base, draft => {1663 const found = draft.items.findLast(item => item.id === 999)1664 expect(found).toBeUndefined()1665 })1666 expect(result).toBe(base)1667 })16681669 test("nested mutations on findLast result", () => {1670 const base = {1671 items: [1672 {id: 1, type: "A", nested: {value: 10}},1673 {id: 2, type: "B", nested: {value: 20}},1674 {id: 3, type: "A", nested: {value: 30}}1675 ]1676 }1677 const result = produce(base, draft => {1678 const found = draft.items.findLast(item => item.type === "A")1679 expect(isDraft(found)).toBe(true)1680 if (found) {1681 found.nested.value = 9991682 }1683 })1684 expect(result.items[2].nested.value).toBe(999)1685 expect(base.items[2].nested.value).toBe(30)1686 })16871688 test("findLast on empty array", () => {1689 const base = {items: []}1690 const result = produce(base, draft => {1691 const found = draft.items.findLast(() => true)1692 expect(found).toBeUndefined()1693 })1694 expect(result).toBe(base)1695 })1696 })16971698 describe("comparison: filter vs concat behavior", () => {1699 test("filter returns drafts that can affect original", () => {1700 const base = {1701 items: [1702 {id: 1, value: 10},1703 {id: 2, value: 20}1704 ]1705 }1706 const result = produce(base, draft => {1707 const filtered = draft.items.filter(item => item.id === 1)1708 expect(isDraft(filtered[0])).toBe(true)1709 filtered[0].value = 9991710 })1711 expect(result.items[0].value).toBe(999)1712 })17131714 // Behavior differs based on array methods plugin1715 if (useArrayMethods) {1716 test("concat returns base values that cannot affect original (with plugin)", () => {1717 const base = {items: [{id: 1, value: 10}]}1718 const result = produce(base, draft => {1719 const concatenated = draft.items.concat()1720 // With plugin: concat returns base values, not drafts1721 expect(isDraft(concatenated[0])).toBe(false)1722 // Attempting to mutate won't affect the draft1723 // (would throw if autoFreeze is on, or just not be tracked)1724 })1725 expect(result).toBe(base)1726 })1727 } else {1728 test("concat returns drafts that can affect original (default behavior)", () => {1729 const base = {items: [{id: 1, value: 10}]}1730 const result = produce(base, draft => {1731 const concatenated = draft.items.concat()1732 // Without plugin: concat returns draft proxies via get trap1733 expect(isDraft(concatenated[0])).toBe(true)1734 // Mutations to concatenated items ARE tracked1735 concatenated[0].value = 9991736 })1737 expect(result.items[0].value).toBe(999)1738 })1739 }1740 })17411742 describe("combined operations", () => {1743 test("chain filter then map then mutate", () => {1744 const base = createTestData()1745 const result = produce(base, draft => {
69 unmodified lines
1815 })1816 expect(result.items[0].value).toBe(999)1817 })18181217 test("mutation during filter callback", () => {1218 const base = createTestData()1219 const result = produce(base, draft => {1220 const filtered = draft.items.filter(item => {1221 // Verify items in filter callback are drafts1222 expect(isDraft(item)).toBe(true)1223 item.touched = true1224 return item.value > 251225 })1226 expect(filtered).toHaveLength(3)1227 })1228 expect(result.items[0].touched).toBe(true)1229 expect(result.items[3].touched).toBe(true)1230 // Verify base state unchanged1231 expect(base.items[0].touched).toBeUndefined()1232 })12331819 test("primitive array filter", () => {1820 const base = {numbers: [1, 2, 3, 4, 5]}1821 const result = produce(base, draft => {1822 const filtered = draft.numbers.filter(n => n > 2)
2311 unmodified lines
modified:perf-testing/immutability-benchmarks.mjs+21 added-4 removed
7 unmodified lines
8import {produce as produce9, setAutoFreeze as setAutoFreeze9} from "immer9"9import {produce as produce10, setAutoFreeze as setAutoFreeze10} from "immer10"10import {11 produce as produce10Perf,12 setAutoFreeze as setAutoFreeze10Perf13 // Uncomment when using a build of Immer that exposes this function,14 // and enable the corresponding line in the setStrictIteration object below.15 // setUseStrictIteration as setUseStrictIteration10Perf12 setAutoFreeze as setAutoFreeze10Perf,13 enableArrayMethods as enableArrayMethods10Perf14} from "immer10Perf"15import {create as produceMutative} from "mutative"16import {17 produce as produceMutativeCompat,
218 unmodified lines
236 structura: noop,237 limu: noop238}239240const setEnableArrayMethods = {241 vanilla: noop,242 immer5: noop,243 immer6: noop,244 immer7: noop,245 immer8: noop,246 immer9: noop,247 immer10: noop,248 immer10Perf: enableArrayMethods10Perf,249 mutative: noop,250 mutativeCompat: noop,251 structura: noop,252 limu: noop253}254255// RTKQ-style separate reducer functions (simulating separate RTK slices)256const updateQueries = (queries, action) => {257 switch (action.type) {258 case "rtkq/pending":
354 unmodified lines
613614 function benchMethod() {615 setAutoFreezes[version](freeze)616 setStrictIteration[version](false)617 setEnableArrayMethods[version]()618 for (let i = 0; i < MAX; i++) {619 reducers[version](initialState, actions[action](i))620 }621 setAutoFreezes[version](false)
26 unmodified lines
648649 function benchMethod() {650 setAutoFreezes[version](freeze)651 setStrictIteration[version](false)652 setEnableArrayMethods[version]()653654 let currentState = createInitialState()655656 // Perform multiple operations on the same evolving state
20 unmodified lines
677678 function benchMethod() {679 setAutoFreezes[version](freeze)680 setStrictIteration[version](false)681 setEnableArrayMethods[version]()682683 let state = createInitialState()684685 // Perform a sequence of different operations (typical workflow)
21 unmodified lines
707708 function benchMethod() {709 setAutoFreezes[version](freeze)710 setStrictIteration[version](false)711 setEnableArrayMethods[version]()712713 let state = createInitialState()714 // Use smaller array size for RTKQ benchmark due to exponential scaling715 // 100 items = ~15ms, 200 items = ~32ms, so 10000 would be impractical
586 unmodified lines
added:perf-testing/immutability-profiling.mjs+562 added
1/* eslint-disable no-inner-declarations */2import {produce, setAutoFreeze, enableArrayMethods} from "../dist/immer.mjs"34enableArrayMethods()5// ============================================================================6// CONFIGURATION7// ============================================================================89const PROFILING_CONFIG = {10 // How many times to run each scenario (can be overridden via CLI)11 iterations: parseInt(process.argv[2]) || 100,1213 // Which scenarios to run14 scenarios: [15 // Single operations16 "add",17 "remove",18 "update",19 "update-high",20 "update-multiple",21 "remove-high",22 "update-largeObject1",23 "update-largeObject2",24 "concat",25 "mapNested",26 "sortById-reverse",27 "reverse-array",2829 // Reuse scenarios (state evolution)30 "update-reuse",31 "update-high-reuse",32 "remove-reuse",33 "remove-high-reuse",34 "update-largeObject1-reuse",35 "update-largeObject2-reuse",3637 // Complex sequences38 "mixed-sequence",39 "rtkq-sequence"40 ]41}4243const BENCHMARK_CONFIG = {44 arraySize: 100,45 nestedArraySize: 10,46 largeObjectSize1: 1000,47 largeObjectSize2: 3000,48 multiUpdateCount: 5,49 reuseStateIterations: 1050}5152const MAX = 15354// ============================================================================55// UTILITY FUNCTIONS56// ============================================================================5758function createInitialState(arraySize = BENCHMARK_CONFIG.arraySize) {59 const initialState = {60 largeArray: Array.from({length: arraySize}, (_, i) => ({61 id: i,62 value: Math.random(),63 nested: {key: `key-${i}`, data: Math.random()},64 moreNested: {65 items: Array.from(66 {length: BENCHMARK_CONFIG.nestedArraySize},67 (_, i) => ({id: i, name: String(i)})68 )69 }70 })),71 otherData: Array.from({length: arraySize}, (_, i) => ({72 id: i,73 name: `name-${i}`,74 isActive: i % 2 === 075 })),76 largeObject1: createLargeObject(BENCHMARK_CONFIG.largeObjectSize1),77 largeObject2: createLargeObject(BENCHMARK_CONFIG.largeObjectSize2),78 api: {79 queries: {},80 provided: {81 keys: {}82 },83 subscriptions: {}84 }85 }86 return initialState87}8889function createLargeObject(size = 100) {90 const obj = {}91 for (let i = 0; i < size; i++) {92 obj[`property${i}`] = {93 id: i,94 value: Math.random(),95 name: `item-${i}`,96 active: i % 2 === 097 }98 }99 return obj100}101102const getValidIndex = (arraySize = BENCHMARK_CONFIG.arraySize) => {103 return Math.min(arraySize - 2, Math.max(0, arraySize - 2))104}105106const getValidId = (arraySize = BENCHMARK_CONFIG.arraySize) => {107 return Math.min(arraySize - 2, Math.max(0, arraySize - 2))108}109110// ============================================================================111// ACTION CREATORS112// ============================================================================113114const add = index => ({115 type: "test/addItem",116 payload: {id: index, value: index, nested: {data: index}}117})118119const remove = index => ({type: "test/removeItem", payload: index})120121const update = index => ({122 type: "test/updateItem",123 payload: {id: index, value: index, nestedData: index}124})125126const updateLargeObject1 = index => ({127 type: "test/updateLargeObject1",128 payload: {value: index}129})130131const updateLargeObject2 = index => ({132 type: "test/updateLargeObject2",133 payload: {value: index}134})135136const concat = index => ({137 type: "test/concatArray",138 payload: Array.from({length: 500}, (_, i) => ({id: i, value: index}))139})140141const mapNested = () => ({142 type: "test/mapNested"143})144145const updateHigh = index => ({146 type: "test/updateHighIndex",147 payload: {148 id:149 Math.floor(BENCHMARK_CONFIG.arraySize * 0.8) +150 (index % Math.floor(BENCHMARK_CONFIG.arraySize * 0.2)),151 value: index,152 nestedData: index153 }154})155156const updateMultiple = index => ({157 type: "test/updateMultiple",158 payload: Array.from({length: BENCHMARK_CONFIG.multiUpdateCount}, (_, i) => ({159 id: (index + i) % BENCHMARK_CONFIG.arraySize,160 value: index + i,161 nestedData: index + i162 }))163})164165const removeHigh = index => ({166 type: "test/removeHighIndex",167 payload:168 Math.floor(BENCHMARK_CONFIG.arraySize * 0.8) +169 (index % Math.floor(BENCHMARK_CONFIG.arraySize * 0.2))170})171172const sortByIdReverse = () => ({173 type: "test/sortByIdReverse"174})175176const reverseArray = () => ({177 type: "test/reverseArray"178})179180const rtkqPending = index => ({181 type: "rtkq/pending",182 payload: {183 cacheKey: `some("test-${index}-")`,184 requestId: `req-${index}`,185 id: `test-${index}-`186 }187})188189const rtkqResolved = index => ({190 type: "rtkq/resolved",191 payload: {192 cacheKey: `some("test-${index}-")`,193 requestId: `req-${index}`,194 id: `test-${index}-`,195 data: `test-${index}-1`196 }197})198199const actions = {200 add,201 remove,202 update,203 concat,204 mapNested,205 "update-largeObject1": updateLargeObject1,206 "update-largeObject2": updateLargeObject2,207 "update-high": updateHigh,208 "update-multiple": updateMultiple,209 "remove-high": removeHigh,210 "sortById-reverse": sortByIdReverse,211 "reverse-array": reverseArray212}213214// ============================================================================215// REDUCER IMPLEMENTATION216// ============================================================================217218const immerReducer = (state = createInitialState(), action) =>219 produce(state, draft => {220 switch (action.type) {221 case "test/addItem":222 draft.largeArray.push(action.payload)223 break224 case "test/removeItem":225 draft.largeArray.splice(action.payload, 1)226 break227 case "test/updateItem": {228 const item = draft.largeArray.find(229 item => item.id === action.payload.id230 )231 item.value = action.payload.value232 item.nested.data = action.payload.nestedData233 break234 }235 case "test/updateLargeObject1": {236 draft.largeObject1[`propertyAdded${action.payload.value}`] = {237 id: action.payload.value238 }239 break240 }241 case "test/updateLargeObject2": {242 draft.largeObject2[`propertyAdded${action.payload.value}`] = {243 id: action.payload.value244 }245 break246 }247 case "test/concatArray": {248 const length = state.largeArray.length249 const newArray = action.payload.concat(state.largeArray)250 newArray.length = length251 draft.largeArray = newArray252 break253 }254 case "test/mapNested": {255 draft.otherData = draft.largeArray.map(item => item.nested)256 break257 }258 case "test/updateHighIndex": {259 const item = draft.largeArray.find(260 item => item.id === action.payload.id261 )262 if (item) {263 item.value = action.payload.value264 item.nested.data = action.payload.nestedData265 }266 break267 }268 case "test/updateMultiple": {269 action.payload.forEach(update => {270 const item = draft.largeArray.find(item => item.id === update.id)271 if (item) {272 item.value = update.value273 item.nested.data = update.nestedData274 }275 })276 break277 }278 case "test/removeHighIndex": {279 const indexToRemove = draft.largeArray.findIndex(280 item => item.id === action.payload281 )282 if (indexToRemove !== -1) {283 draft.largeArray.splice(indexToRemove, 1)284 }285 break286 }287 case "test/sortByIdReverse": {288 draft.largeArray.sort((a, b) => b.id - a.id)289 break290 }291 case "test/reverseArray": {292 draft.largeArray.reverse()293 break294 }295 case "rtkq/pending": {296 const cacheKey = action.payload.cacheKey297 draft.api.queries[cacheKey] = {298 id: action.payload.id,299 status: "pending",300 data: undefined301 }302 draft.api.provided.keys[cacheKey] = {}303 draft.api.subscriptions[cacheKey] = {304 [action.payload.requestId]: {305 pollingInterval: 0,306 skipPollingIfUnfocused: false307 }308 }309 break310 }311 case "rtkq/resolved": {312 const cacheKey = action.payload.cacheKey313 draft.api.queries[cacheKey].status = "fulfilled"314 draft.api.queries[cacheKey].data = action.payload.data315 break316 }317 }318 })319320// ============================================================================321// SCENARIO FUNCTIONS322// ============================================================================323324// Single operation scenarios - execute once325function scenario_add() {326 const initialState = createInitialState()327 for (let j = 0; j < MAX; j++) {328 immerReducer(initialState, actions.add(j))329 }330}331332function scenario_remove() {333 const initialState = createInitialState()334 for (let j = 0; j < MAX; j++) {335 immerReducer(initialState, actions.remove(j))336 }337}338339function scenario_update() {340 const initialState = createInitialState()341 for (let j = 0; j < MAX; j++) {342 immerReducer(initialState, actions.update(j))343 }344}345346function scenario_update_high() {347 const initialState = createInitialState()348 for (let j = 0; j < MAX; j++) {349 immerReducer(initialState, actions["update-high"](j))350 }351}352353function scenario_update_multiple() {354 const initialState = createInitialState()355 for (let j = 0; j < MAX; j++) {356 immerReducer(initialState, actions["update-multiple"](j))357 }358}359360function scenario_remove_high() {361 const initialState = createInitialState()362 for (let j = 0; j < MAX; j++) {363 immerReducer(initialState, actions["remove-high"](j))364 }365}366367function scenario_update_largeObject1() {368 const initialState = createInitialState()369 for (let j = 0; j < MAX; j++) {370 immerReducer(initialState, actions["update-largeObject1"](j))371 }372}373374function scenario_update_largeObject2() {375 const initialState = createInitialState()376 for (let j = 0; j < MAX; j++) {377 immerReducer(initialState, actions["update-largeObject2"](j))378 }379}380381function scenario_concat() {382 const initialState = createInitialState()383 for (let j = 0; j < MAX; j++) {384 immerReducer(initialState, actions.concat(j))385 }386}387388function scenario_mapNested() {389 const initialState = createInitialState()390 for (let j = 0; j < MAX; j++) {391 immerReducer(initialState, actions.mapNested())392 }393}394395function scenario_sortById_reverse() {396 const initialState = createInitialState()397 for (let j = 0; j < MAX; j++) {398 immerReducer(initialState, actions["sortById-reverse"]())399 }400}401402function scenario_reverse_array() {403 const initialState = createInitialState()404 for (let j = 0; j < MAX; j++) {405 immerReducer(initialState, actions["reverse-array"]())406 }407}408409// Reuse scenarios - execute full state evolution sequence once410function scenario_update_reuse() {411 let currentState = createInitialState()412413 for (let j = 0; j < BENCHMARK_CONFIG.reuseStateIterations; j++) {414 currentState = immerReducer(currentState, actions.update(j))415 }416}417418function scenario_update_high_reuse() {419 let currentState = createInitialState()420421 for (let j = 0; j < BENCHMARK_CONFIG.reuseStateIterations; j++) {422 currentState = immerReducer(currentState, actions["update-high"](j))423 }424}425426function scenario_remove_reuse() {427 let currentState = createInitialState()428429 for (let j = 0; j < BENCHMARK_CONFIG.reuseStateIterations; j++) {430 currentState = immerReducer(currentState, actions.remove(j))431 }432}433434function scenario_remove_high_reuse() {435 let currentState = createInitialState()436437 for (let j = 0; j < BENCHMARK_CONFIG.reuseStateIterations; j++) {438 currentState = immerReducer(currentState, actions["remove-high"](j))439 }440}441442function scenario_update_largeObject1_reuse() {443 let currentState = createInitialState()444445 for (let j = 0; j < BENCHMARK_CONFIG.reuseStateIterations; j++) {446 currentState = immerReducer(currentState, actions["update-largeObject1"](j))447 }448}449450function scenario_update_largeObject2_reuse() {451 let currentState = createInitialState()452453 for (let j = 0; j < BENCHMARK_CONFIG.reuseStateIterations; j++) {454 currentState = immerReducer(currentState, actions["update-largeObject2"](j))455 }456}457458// Complex sequence scenarios - execute full sequence once459function scenario_mixed_sequence() {460 let state = createInitialState()461 state = immerReducer(state, actions.add(1))462 state = immerReducer(state, actions.update(getValidId()))463 state = immerReducer(state, actions["update-high"](2))464 state = immerReducer(state, actions["update-multiple"](3))465 state = immerReducer(state, actions.remove(getValidIndex()))466}467468function scenario_rtkq_sequence() {469 let state = createInitialState()470 const arraySize = 100471472 // Phase 1: Execute all pending actions473 for (let j = 0; j < arraySize; j++) {474 state = immerReducer(state, rtkqPending(j))475 }476477 // Phase 2: Execute all resolved actions478 for (let j = 0; j < arraySize; j++) {479 state = immerReducer(state, rtkqResolved(j))480 }481}482483// ============================================================================484// SCENARIO REGISTRY485// ============================================================================486487const scenarios = {488 // Single operations489 add: scenario_add,490 remove: scenario_remove,491 update: scenario_update,492 "update-high": scenario_update_high,493 "update-multiple": scenario_update_multiple,494 "remove-high": scenario_remove_high,495 "update-largeObject1": scenario_update_largeObject1,496 "update-largeObject2": scenario_update_largeObject2,497 concat: scenario_concat,498 mapNested: scenario_mapNested,499 "sortById-reverse": scenario_sortById_reverse,500 "reverse-array": scenario_reverse_array,501502 // Reuse scenarios503 "update-reuse": scenario_update_reuse,504 "update-high-reuse": scenario_update_high_reuse,505 "remove-reuse": scenario_remove_reuse,506 "remove-high-reuse": scenario_remove_high_reuse,507 "update-largeObject1-reuse": scenario_update_largeObject1_reuse,508 "update-largeObject2-reuse": scenario_update_largeObject2_reuse,509510 // Complex sequences511 "mixed-sequence": scenario_mixed_sequence,512 "rtkq-sequence": scenario_rtkq_sequence513}514515// ============================================================================516// MAIN EXECUTION517// ============================================================================518519function main() {520 // Set freeze to true (default Immer behavior)521 setAutoFreeze(true)522523 console.log("=".repeat(80))524 console.log("IMMER PROFILING SCRIPT (freeze: true)")525 console.log("=".repeat(80))526 console.log(`Iterations per scenario: ${PROFILING_CONFIG.iterations}`)527 console.log(`Total scenarios: ${PROFILING_CONFIG.scenarios.length}`)528 console.log("=".repeat(80))529 console.log()530531 let completed = 0532 for (const scenarioName of PROFILING_CONFIG.scenarios) {533 const scenarioFn = scenarios[scenarioName]534 if (!scenarioFn) {535 console.log(`⚠ Skipping unknown scenario: ${scenarioName}`)536 continue537 }538539 const start = performance.now()540541 // Driver loop handles iterations542 for (let i = 0; i < PROFILING_CONFIG.iterations; i++) {543 scenarioFn()544 }545546 const duration = performance.now() - start547548 completed++549 console.log(550 `[${completed}/${551 PROFILING_CONFIG.scenarios.length552 }] ✓ ${scenarioName} - ${duration.toFixed(2)}ms`553 )554 }555556 console.log()557 console.log("=".repeat(80))558 console.log("Profiling complete!")559 console.log("=".repeat(80))560}561562main()
modified:src/core/finalize.ts+6 added-2 removed
18 unmodified lines
19 Patch,20 latest,21 prepareCopy,22 getFinalValue,23 getValue23 getValue,24 ProxyArrayState25} from "../internal"2627export function processResult(result: any, scope: ImmerScope) {28 scope.unfinalizedDrafts_ = scope.drafts_.length
165 unmodified lines
194function generatePatchesAndFinalize(state: ImmerState, rootScope: ImmerScope) {195 const shouldFinalize =196 state.modified_ &&197 !state.finalized_ &&197 (state.type_ === ArchType.Set || (state.assigned_?.size ?? 0) > 0)198 (state.type_ === ArchType.Set ||199 (state.type_ === ArchType.Array &&200 (state as ProxyArrayState).allIndicesReassigned_) ||201 (state.assigned_?.size ?? 0) > 0)202203 if (shouldFinalize) {204 const {patchPlugin_} = rootScope205 if (patchPlugin_) {
107 unmodified lines
modified:src/core/proxy.ts+29 added-1 removed
21 unmodified lines
22 WRITABLE,23 CONFIGURABLE,24 ENUMERABLE,25 VALUE,26 isArray26 isArray,27 isArrayIndex28} from "../internal"2930interface ProxyBaseState extends ImmerBaseState {31 parent_?: ImmerState
11 unmodified lines
43 type_: ArchType.Array44 base_: AnyArray45 copy_: AnyArray | null46 draft_: Drafted<AnyArray, ProxyArrayState>47 operationMethod?: string48 allIndicesReassigned_?: boolean49}5051type ProxyState = ProxyObjectState | ProxyArrayState52
58 unmodified lines
111export const objectTraps: ProxyHandler<ProxyState> = {112 get(state, prop) {113 if (prop === DRAFT_STATE) return state114115 let arrayPlugin = state.scope_.arrayMethodsPlugin_116 const isArrayWithStringProp =117 state.type_ === ArchType.Array && typeof prop === "string"118 // Intercept array methods so that we can override119 // behavior and skip proxy creation for perf120 if (isArrayWithStringProp) {121 if (arrayPlugin?.isArrayOperationMethod(prop)) {122 return arrayPlugin.createMethodInterceptor(state, prop)123 }124 }125126 const source = latest(state)127 if (!has(source, prop, state.type_)) {128 // non-existing or non-own property...129 return readPropFromProto(state, source, prop)
1 unmodified line
131 const value = source[prop]132 if (state.finalized_ || !isDraftable(value)) {133 return value134 }135136 // During mutating array operations, defer proxy creation for array elements137 // This optimization avoids creating unnecessary proxies during sort/reverse138 if (139 isArrayWithStringProp &&140 (state as ProxyArrayState).operationMethod &&141 arrayPlugin?.isMutatingArrayMethod(142 (state as ProxyArrayState).operationMethod!143 ) &&144 isArrayIndex(prop)145 ) {146 // Return raw value during mutating operations, create proxy only if modified147 return value148 }149 // Check for existing draft in modified state.150 // Assigned values are never drafted. This catches any drafts we created, too.151 if (value === peek(state.base_, prop)) {152 prepareCopy(state)
183 unmodified lines
modified:src/core/scope.ts+7 added-1 removed
added:src/plugins/arrayMethods.ts+395 added
1import {2 PluginArrayMethods,3 latest,4 loadPlugin,5 markChanged,6 prepareCopy,7 ProxyArrayState8} from "../internal"910/**11 * Methods that directly modify the array in place.12 * These operate on the copy without creating per-element proxies:13 * - `push`, `pop`: Add/remove from end14 * - `shift`, `unshift`: Add/remove from start (marks all indices reassigned)15 * - `splice`: Add/remove at arbitrary position (marks all indices reassigned)16 * - `reverse`, `sort`: Reorder elements (marks all indices reassigned)17 */18type MutatingArrayMethod =19 | "push"20 | "pop"21 | "shift"22 | "unshift"23 | "splice"24 | "reverse"25 | "sort"2627/**28 * Methods that read from the array without modifying it.29 * These fall into distinct categories based on return semantics:30 *31 * **Subset operations** (return drafts - mutations propagate):32 * - `filter`, `slice`: Return array of draft proxies33 * - `find`, `findLast`: Return single draft proxy or undefined34 *35 * **Transform operations** (return base values - mutations don't track):36 * - `concat`, `flat`: Create new structures, not subsets of original37 *38 * **Primitive-returning** (no draft needed):39 * - `findIndex`, `findLastIndex`, `indexOf`, `lastIndexOf`: Return numbers40 * - `some`, `every`, `includes`: Return booleans41 * - `join`, `toString`, `toLocaleString`: Return strings42 */43type NonMutatingArrayMethod =44 | "filter"45 | "slice"46 | "concat"47 | "flat"48 | "find"49 | "findIndex"50 | "findLast"51 | "findLastIndex"52 | "some"53 | "every"54 | "indexOf"55 | "lastIndexOf"56 | "includes"57 | "join"58 | "toString"59 | "toLocaleString"6061/** Union of all array operation methods handled by the plugin. */62export type ArrayOperationMethod = MutatingArrayMethod | NonMutatingArrayMethod6364/**65 * Enables optimized array method handling for Immer drafts.66 *67 * This plugin overrides array methods to avoid unnecessary Proxy creation during iteration,68 * significantly improving performance for array-heavy operations.69 *70 * **Mutating methods** (push, pop, shift, unshift, splice, sort, reverse):71 * Operate directly on the copy without creating per-element proxies.72 *73 * **Non-mutating methods** fall into categories:74 * - **Subset operations** (filter, slice, find, findLast): Return draft proxies - mutations track75 * - **Transform operations** (concat, flat): Return base values - mutations don't track76 * - **Primitive-returning** (indexOf, includes, some, every, etc.): Return primitives77 *78 * **Important**: Callbacks for overridden methods receive base values, not drafts.79 * This is the core performance optimization.80 *81 * @example82 * ```ts83 * import { enableArrayMethods, produce } from "immer"84 *85 * enableArrayMethods()86 *87 * const next = produce(state, draft => {88 * // Optimized - no proxy creation per element89 * draft.items.sort((a, b) => a.value - b.value)90 *91 * // filter returns drafts - mutations propagate92 * const filtered = draft.items.filter(x => x.value > 5)93 * filtered[0].value = 999 // Affects draft.items[originalIndex]94 * })95 * ```96 *97 * @see https://immerjs.github.io/immer/array-methods98 */99export function enableArrayMethods() {100 const SHIFTING_METHODS = new Set<MutatingArrayMethod>(["shift", "unshift"])101102 const QUEUE_METHODS = new Set<MutatingArrayMethod>(["push", "pop"])103104 const RESULT_RETURNING_METHODS = new Set<MutatingArrayMethod>([105 ...QUEUE_METHODS,106 ...SHIFTING_METHODS107 ])108109 const REORDERING_METHODS = new Set<MutatingArrayMethod>(["reverse", "sort"])110111 // Optimized method detection using array-based lookup112 const MUTATING_METHODS = new Set<MutatingArrayMethod>([113 ...RESULT_RETURNING_METHODS,114 ...REORDERING_METHODS,115 "splice"116 ])117118 const FIND_METHODS = new Set<NonMutatingArrayMethod>(["find", "findLast"])119120 const NON_MUTATING_METHODS = new Set<NonMutatingArrayMethod>([121 "filter",122 "slice",123 "concat",124 "flat",125 ...FIND_METHODS,126 "findIndex",127 "findLastIndex",128 "some",129 "every",130 "indexOf",131 "lastIndexOf",132 "includes",133 "join",134 "toString",135 "toLocaleString"136 ])137138 // Type guard for method detection139 function isMutatingArrayMethod(140 method: string141 ): method is MutatingArrayMethod {142 return MUTATING_METHODS.has(method as any)143 }144145 function isNonMutatingArrayMethod(146 method: string147 ): method is NonMutatingArrayMethod {148 return NON_MUTATING_METHODS.has(method as any)149 }150151 function isArrayOperationMethod(152 method: string153 ): method is ArrayOperationMethod {154 return isMutatingArrayMethod(method) || isNonMutatingArrayMethod(method)155 }156157 function enterOperation(158 state: ProxyArrayState,159 method: ArrayOperationMethod160 ) {161 state.operationMethod = method162 }163164 function exitOperation(state: ProxyArrayState) {165 state.operationMethod = undefined166 }167168 // Shared utility functions for array method handlers169 function executeArrayMethod<T>(170 state: ProxyArrayState,171 operation: () => T,172 markLength = true173 ): T {174 prepareCopy(state)175 const result = operation()176 markChanged(state)177 if (markLength) state.assigned_!.set("length", true)178 return result179 }180181 function markAllIndicesReassigned(state: ProxyArrayState) {182 state.allIndicesReassigned_ = true183 }184185 function normalizeSliceIndex(index: number, length: number): number {186 if (index < 0) {187 return Math.max(length + index, 0)188 }189 return Math.min(index, length)190 }191192 /**193 * Handles mutating operations that add/remove elements (push, pop, shift, unshift, splice).194 *195 * Operates directly on `state.copy_` without creating per-element proxies.196 * For shifting methods (shift, unshift), marks all indices as reassigned since197 * indices shift.198 *199 * @returns For push/pop/shift/unshift: the native method result. For others: the draft.200 */201 function handleSimpleOperation(202 state: ProxyArrayState,203 method: string,204 args: any[]205 ) {206 return executeArrayMethod(state, () => {207 const result = (state.copy_! as any)[method](...args)208209 // Handle index reassignment for shifting methods210 if (SHIFTING_METHODS.has(method as MutatingArrayMethod)) {211 markAllIndicesReassigned(state)212 }213214 // Return appropriate value based on method215 return RESULT_RETURNING_METHODS.has(method as MutatingArrayMethod)216 ? result217 : state.draft_218 })219 }220221 /**222 * Handles reordering operations (reverse, sort) that change element order.223 *224 * Operates directly on `state.copy_` and marks all indices as reassigned225 * since element positions change. Does not mark length as changed since226 * these operations preserve array length.227 *228 * @returns The draft proxy for method chaining.229 */230 function handleReorderingOperation(231 state: ProxyArrayState,232 method: string,233 args: any[]234 ) {235 return executeArrayMethod(236 state,237 () => {238 ;(state.copy_! as any)[method](...args)239 markAllIndicesReassigned(state)240 return state.draft_241 },242 false243 ) // Don't mark length as changed244 }245246 /**247 * Creates an interceptor function for a specific array method.248 *249 * The interceptor wraps array method calls to:250 * 1. Set `state.operationMethod` flag during execution (allows proxy `get` trap251 * to detect we're inside an optimized method and skip proxy creation)252 * 2. Route to appropriate handler based on method type253 * 3. Clean up the operation flag in `finally` block254 *255 * The `operationMethod` flag is the key mechanism that enables the proxy's `get`256 * trap to return base values instead of creating nested proxies during iteration.257 *258 * @param state - The proxy array state259 * @param originalMethod - Name of the array method being intercepted260 * @returns Interceptor function that handles the method call261 */262 function createMethodInterceptor(263 state: ProxyArrayState,264 originalMethod: string265 ) {266 return function interceptedMethod(...args: any[]) {267 // Enter operation mode - this flag tells the proxy's get trap to return268 // base values instead of creating nested proxies during iteration269 const method = originalMethod as ArrayOperationMethod270 enterOperation(state, method)271272 try {273 // Check if this is a mutating method274 if (isMutatingArrayMethod(method)) {275 // Direct method dispatch - no configuration lookup needed276 if (RESULT_RETURNING_METHODS.has(method)) {277 return handleSimpleOperation(state, method, args)278 }279 if (REORDERING_METHODS.has(method)) {280 return handleReorderingOperation(state, method, args)281 }282283 if (method === "splice") {284 const res = executeArrayMethod(state, () =>285 state.copy_!.splice(...(args as [number, number, ...any[]]))286 )287 markAllIndicesReassigned(state)288 return res289 }290 } else {291 // Handle non-mutating methods292 return handleNonMutatingOperation(state, method, args)293 }294 } finally {295 // Always exit operation mode - must be in finally to handle exceptions296 exitOperation(state)297 }298 }299 }300301 /**302 * Handles non-mutating array methods with different return semantics.303 *304 * **Subset operations** return draft proxies for mutation tracking:305 * - `filter`, `slice`: Return `state.draft_[i]` for each selected element306 * - `find`, `findLast`: Return `state.draft_[i]` for the found element307 *308 * This allows mutations on returned elements to propagate back to the draft:309 * ```ts310 * const filtered = draft.items.filter(x => x.value > 5)311 * filtered[0].value = 999 // Mutates draft.items[originalIndex]312 * ```313 *314 * **Transform operations** return base values (no draft tracking):315 * - `concat`, `flat`: These create NEW arrays rather than selecting subsets.316 * Since the result structure differs from the original, tracking mutations317 * back to specific draft indices would be impractical/impossible.318 *319 * **Primitive operations** return the native result directly:320 * - `indexOf`, `includes`, `some`, `every`, `join`, etc.321 *322 * @param state - The proxy array state323 * @param method - The non-mutating method name324 * @param args - Arguments passed to the method325 * @returns Drafts for subset operations, base values for transforms, primitives otherwise326 */327 function handleNonMutatingOperation(328 state: ProxyArrayState,329 method: NonMutatingArrayMethod,330 args: any[]331 ) {332 const source = latest(state)333334 // Methods that return arrays with selected items - need to return drafts335 if (method === "filter") {336 const predicate = args[0]337 const result: any[] = []338339 // First pass: call predicate on base values to determine which items pass340 for (let i = 0; i < source.length; i++) {341 if (predicate(source[i], i, source)) {342 // Only create draft for items that passed the predicate343 result.push(state.draft_[i])344 }345 }346347 return result348 }349350 if (FIND_METHODS.has(method)) {351 const predicate = args[0]352 const isForward = method === "find"353 const step = isForward ? 1 : -1354 const start = isForward ? 0 : source.length - 1355356 for (let i = start; i >= 0 && i < source.length; i += step) {357 if (predicate(source[i], i, source)) {358 return state.draft_[i]359 }360 }361 return undefined362 }363364 if (method === "slice") {365 const rawStart = args[0] ?? 0366 const rawEnd = args[1] ?? source.length367368 // Normalize negative indices369 const start = normalizeSliceIndex(rawStart, source.length)370 const end = normalizeSliceIndex(rawEnd, source.length)371372 const result: any[] = []373374 // Return drafts for items in the slice range375 for (let i = start; i < end; i++) {376 result.push(state.draft_[i])377 }378379 return result380 }381382 // For other methods, call on base array directly:383 // - indexOf, includes, join, toString: Return primitives, no draft needed384 // - concat, flat: Return NEW arrays (not subsets). Elements are base values.385 // This is intentional - concat/flat create new data structures rather than386 // selecting subsets of the original, making draft tracking impractical.387 return source[method as keyof typeof Array.prototype](...args)388 }389390 loadPlugin(PluginArrayMethods, {391 createMethodInterceptor,392 isArrayOperationMethod,393 isMutatingArrayMethod394 })395}
modified:src/plugins/patches.ts+5 added-1 removed
182 unmodified lines
183 ;[base_, copy_] = [copy_, base_]184 ;[patches, inversePatches] = [inversePatches, patches]185 }186187 const allReassigned = state.allIndicesReassigned_ === true188189 // Process replaced indices.190 for (let i = 0; i < base_.length; i++) {191 const copiedItem = copy_[i]192 const baseItem = base_[i]191 if (assigned_?.get(i.toString()) && copiedItem !== baseItem) {193194 const isAssigned = allReassigned || assigned_?.get(i.toString())195 if (isAssigned && copiedItem !== baseItem) {196 const childState = copiedItem?.[DRAFT_STATE]197 if (childState && childState.modified_) {198 // Skip - let the child generate its own patches199 continue
232 unmodified lines
modified:src/types/index.js.flow+1 added
105 unmodified lines
106declare export function finishDraft<T>(base: T, listener?: PatchListener): T107108declare export function enableMapSet(): void109declare export function enablePatches(): void110declare export function enableArrayMethods(): void111112declare export function freeze<T>(obj: T, freeze?: boolean): T
modified:src/utils/common.ts+5 added
169 unmodified lines
170171export let isBoolean = (target: any): target is boolean =>172 typeof target === "boolean"173174export function isArrayIndex(value: string | number): value is number | string {175 const n = +value176 return Number.isInteger(n) && String(n) === value177}178179export let getProxyDraft = <T extends any>(value: T): ImmerState | null => {180 if (!isObjectish(value)) return null181 return (value as {[DRAFT_STATE]: any})?.[DRAFT_STATE]182}
104 unmodified lines
modified:src/utils/plugins.ts+14 added-1 removed
5 unmodified lines
6 AnyMap,7 AnySet,8 ArchType,9 die,10 ImmerScope10 ImmerScope,11 ProxyArrayState12} from "../internal"1314export const PluginMapSet = "MapSet"15export const PluginPatches = "Patches"16export const PluginArrayMethods = "ArrayMethods"1718export type PatchesPlugin = {19 generatePatches_(20 state: ImmerState,
14 unmodified lines
35 proxySet_<T extends AnySet>(target: T, parent?: ImmerState): [T, ImmerState]36 fixSetContents: (state: ImmerState) => void37}3839export type ArrayMethodsPlugin = {40 createMethodInterceptor: (state: ProxyArrayState, method: string) => Function41 isArrayOperationMethod: (method: string) => boolean42 isMutatingArrayMethod: (method: string) => boolean43}4445/** Plugin utilities */46const plugins: {47 Patches?: PatchesPlugin48 MapSet?: MapSetPlugin49 ArrayMethods?: ArrayMethodsPlugin50} = {}5152type Plugins = typeof plugins53
10 unmodified lines
6465export let isPluginLoaded = <K extends keyof Plugins>(pluginKey: K): boolean =>66 !!plugins[pluginKey]6768export let clearPlugin = <K extends keyof Plugins>(pluginKey: K): void => {69 delete plugins[pluginKey]70}7172export function loadPlugin<K extends keyof Plugins>(73 pluginKey: K,74 implementation: Plugins[K]75): void {
24 unmodified lines
modified:src/immer.ts+1 added
121 unmodified lines
122export {Immer}123124export {enablePatches} from "./plugins/patches"125export {enableMapSet} from "./plugins/mapset"126export {enableArrayMethods} from "./plugins/arrayMethods"
modified:website/docs/api.md+1 added
14 unmodified lines
15| `castImmutable` | Converts any mutable type to its immutable counterpart. This is just a cast and doesn't actually do anything. | [TypeScript](./typescript.mdx) |16| `createDraft` | Given a base state, creates a mutable draft for which any modifications will be recorded | [Async](./async.mdx) |17| `current` | Given a draft object (doesn't have to be a tree root), takes a snapshot of the current state of the draft | [Current](./current.md) |18| `Draft<T>` | Exposed TypeScript type to convert an immutable type to a mutable type | [TypeScript](./typescript.mdx) |19| `enableArrayMethods()` | Enables optimized array method handling for improved performance with array-heavy operations. | [Array Methods](./array-methods.md) |20| `enableMapSet()` | Enables support for `Map` and `Set` collections. | [Installation](./installation.mdx#pick-your-immer-version) |21| `enablePatches()` | Enables support for JSON patches. | [Installation](./installation#pick-your-immer-version) |22| `finishDraft` | Given an draft created using `createDraft`, seals the draft and produces and returns the next immutable state that captures all the changes | [Async](./async.mdx) |23| `freeze(obj, deep?)` | Freezes draftable objects. Returns the original object. By default freezes shallowly, but if the second argument is `true` it will freeze recursively. |
21 unmodified lines
added:website/docs/array-methods.md+277 added
1---2id: array-methods3title: Array Methods Plugin4---56<center>7<div data-ea-publisher="immerjs" data-ea-type="image" className="horizontal bordered"></div>8</center>910## Overview1112The Array Methods Plugin (`enableArrayMethods()`) optimizes array operations within Immer producers by avoiding unnecessary Proxy creation during iteration. This provides significant performance improvements for array-heavy operations.1314**Why does this matter?** Without the plugin, every array element access during iteration (e.g., in `filter`, `find`, `slice`) creates a Proxy object. For a 1000-element array, this means 1000+ proxy trap invocations just to iterate. With the plugin enabled, callbacks receive base (non-proxied) values, and proxies are only created as needed for mutation tracking.1516## Installation1718Enable the plugin once at your application's entry point:1920```javascript21import {enableArrayMethods} from "immer"2223enableArrayMethods()24```2526This adds approximately **2KB** to your bundle size.2728## Mutating Methods2930These methods modify the array in-place and operate directly on the draft's internal copy without creating per-element proxies:3132| Method | Returns | Description |33| ----------- | ---------------- | ------------------------------------- |34| `push()` | New length | Adds elements to the end |35| `pop()` | Removed element | Removes and returns the last element |36| `shift()` | Removed element | Removes and returns the first element |37| `unshift()` | New length | Adds elements to the beginning |38| `splice()` | Removed elements | Adds/removes elements at any position |39| `sort()` | The draft array | Sorts elements in place |40| `reverse()` | The draft array | Reverses the array in place |4142```javascript43import {produce, enableArrayMethods} from "immer"4445enableArrayMethods()4647const base = {items: [3, 1, 4, 1, 5]}4849const result = produce(base, draft => {50 draft.items.push(9) // Adds 9 to end51 draft.items.sort() // Sorts: [1, 1, 3, 4, 5, 9]52 draft.items.reverse() // Reverses: [9, 5, 4, 3, 1, 1]53})54```5556## Non-Mutating Methods5758Non-mutating methods are categorized based on what they return:5960### Subset Operations (Return Drafts)6162These methods select items that exist in the original array and **create draft proxies** for the returned items. The callbacks receive **base values** (the optimization), but the **returned array** contains newly created draft proxies that point back to the original positions. **Mutations to returned items WILL affect the draft state.**6364| Method | Returns | Drafts? |65| ------------ | ---------------------------------- | ------- |66| `filter()` | Array of matching items | ✅ Yes |67| `slice()` | Array of items in range | ✅ Yes |68| `find()` | First matching item or `undefined` | ✅ Yes |69| `findLast()` | Last matching item or `undefined` | ✅ Yes |7071```javascript72const base = {73 items: [74 {id: 1, value: 10},75 {id: 2, value: 20},76 {id: 3, value: 30}77 ]78}7980const result = produce(base, draft => {81 // filter returns drafts - mutations track back to original82 const filtered = draft.items.filter(item => item.value > 15)83 filtered[0].value = 999 // This WILL affect draft.items[1]8485 // find returns a draft - mutations track back86 const found = draft.items.find(item => item.id === 3)87 if (found) {88 found.value = 888 // This WILL affect draft.items[2]89 }9091 // slice returns drafts92 const sliced = draft.items.slice(0, 2)93 sliced[0].value = 777 // This WILL affect draft.items[0]94})9596console.log(result.items[0].value) // 77797console.log(result.items[1].value) // 99998console.log(result.items[2].value) // 88899```100101### Transform Operations (Return Base Values)102103These methods create **new arrays** that may include external items or restructured data. They return **base values**, NOT drafts. **Mutations to returned items will NOT track back to the draft state.**104105| Method | Returns | Drafts? |106| ---------- | ------------------- | ------- |107| `concat()` | New combined array | ❌ No |108| `flat()` | New flattened array | ❌ No |109110```javascript111const base = {items: [{id: 1, value: 10}]}112113const result = produce(base, draft => {114 // concat returns base values - mutations DON'T track115 const concatenated = draft.items.concat([{id: 2, value: 20}])116 concatenated[0].value = 999 // This will NOT affect draft.items[0]117118 // To actually use concat results, assign them:119 draft.items = draft.items.concat([{id: 2, value: 20}])120})121122// Original unchanged because concat result wasn't assigned123console.log(result.items[0].value) // 10 (unchanged)124```125126**Why the distinction?**127128- **Subset operations** (`filter`, `slice`, `find`) select items that exist in the original array. Returning drafts allows mutations to propagate back to the source.129- **Transform operations** (`concat`, `flat`) create new data structures that may include external items or restructured data, making draft tracking impractical.130131### Primitive-Returning Methods132133These methods return primitive values (numbers, booleans, strings). No tracking issues since primitives aren't draftable:134135| Method | Returns |136| ------------------ | -------------------- |137| `indexOf()` | Number (index or -1) |138| `lastIndexOf()` | Number (index or -1) |139| `includes()` | Boolean |140| `some()` | Boolean |141| `every()` | Boolean |142| `findIndex()` | Number (index or -1) |143| `findLastIndex()` | Number (index or -1) |144| `join()` | String |145| `toString()` | String |146| `toLocaleString()` | String |147148```javascript149const base = {150 items: [151 {id: 1, active: true},152 {id: 2, active: false}153 ]154}155156const result = produce(base, draft => {157 const index = draft.items.findIndex(item => item.id === 2)158 const hasActive = draft.items.some(item => item.active)159 const allActive = draft.items.every(item => item.active)160161 console.log(index) // 1162 console.log(hasActive) // true163 console.log(allActive) // false164})165```166167## Methods NOT Overridden168169The following methods are **not** intercepted by the plugin and work through standard Proxy behavior. Callbacks receive drafts, and mutations track normally:170171| Method | Description |172| --------------- | --------------------------------- |173| `map()` | Transform each element |174| `flatMap()` | Map then flatten |175| `forEach()` | Execute callback for each element |176| `reduce()` | Reduce to single value |177| `reduceRight()` | Reduce from right to left |178179```javascript180const base = {181 items: [182 {id: 1, value: 10, nested: {count: 0}},183 {id: 2, value: 20, nested: {count: 0}}184 ]185}186187const result = produce(base, draft => {188 // forEach receives drafts - mutations work normally189 draft.items.forEach(item => {190 item.value *= 2191 })192193 // map is NOT overridden - callbacks receive drafts194 // The returned array items are also drafts (extracted from draft.items)195 const mapped = draft.items.map(item => item.nested)196 // Mutations to the result array propagate back197 mapped[0].count = 999 // ✅ This affects draft.items[0].nested.count198})199200console.log(result.items[0].nested.count) // 999201```202203## Callback Behavior204205For overridden methods, callbacks receive **base values** (not drafts). This is the core optimization - it avoids creating proxies for every element during iteration.206207```javascript208const base = {209 items: [210 {id: 1, value: 10},211 {id: 2, value: 20}212 ]213}214215produce(base, draft => {216 draft.items.filter(item => {217 // `item` is a base value here, NOT a draft218 // Reading properties works fine219 return item.value > 15220221 // But direct mutation here won't be tracked:222 // item.value = 999 // ❌ Won't affect draft223 })224225 // Instead, use the returned draft:226 const filtered = draft.items.filter(item => item.value > 15)227 filtered[0].value = 999 // ✅ This works because filtered[0] is a draft228})229```230231## Method Return Behavior Summary232233| Category | Methods | Returns | Mutations Track? |234| --- | --- | --- | --- |235| **Subset** | `filter`, `slice`, `find`, `findLast` | Draft proxies | ✅ Yes |236| **Transform** | `concat`, `flat` | Base values | ❌ No |237| **Primitive** | `indexOf`, `includes`, `some`, `every`, `findIndex`, `findLastIndex`, `lastIndexOf`, `join`, `toString`, `toLocaleString` | Primitives | N/A |238| **Mutating** | `push`, `pop`, `shift`, `unshift`, `splice`, `sort`, `reverse` | Various | ✅ Yes (modifies draft) |239| **Not Overridden** | `map`, `flatMap`, `forEach`, `reduce`, `reduceRight` | Standard behavior | ✅ Yes (callbacks get drafts) |240241## When to Use242243Enable the Array Methods Plugin when:244245- Your application has significant array iteration within producers246- You frequently use methods like `filter`, `find`, `some`, `every` on large arrays247- Performance profiling shows array operations as a bottleneck248249The plugin is most beneficial for:250251- Large arrays (100+ elements)252- Frequent producer calls with array operations253- Read-heavy operations (filtering, searching) where most elements aren't modified254255## Performance Benefit256257**Without the plugin:**258259- Every array element access during iteration creates a Proxy260- A `filter()` on 1000 elements = 1000+ proxy creations261262**With the plugin:**263264- Callbacks receive base values directly265- Proxies only created for the specific elements you actually mutate, or that match filtering predicates266267```javascript268// Without plugin: ~3000+ proxy trap invocations269// With plugin: ~10-20 proxy trap invocations270const result = produce(largeState, draft => {271 const filtered = draft.items.filter(x => x.value > threshold)272 // Only items you mutate get proxied273 filtered.forEach(item => {274 item.processed = true275 })276})277```
modified:website/docs/installation.mdx+8 added-6 removed
28 unmodified lines
29The following features can be opt-in to:3031| Feature | Description | Method to call |32| --- | --- | --- |33| [Array Methods optimization](./array-methods.md) | Optimizes array method handling for improved performance with array-heavy operations | `enableArrayMethods()` |34| [ES2015 Map and Set support](./complex-objects.md) | To enable Immer to operate on the native `Map` and `Set` collections, enable this feature | `enableMapSet()` |35| [JSON Patch support](./patches.mdx) | Immer can keep track of all the changes you make to draft objects. This can be useful for communicating changes using JSON patches | `enablePatches()` |3637For example, if you want to use `produce` on a `Map`, you need to enable this feature once during the start of your application:
18 unmodified lines
56expect(usersById_v1.get("michel").country).toBe("NL")57expect(usersById_v2.get("michel").country).toBe("UK")58```5959Vanilla Immer kicks in at ~3KB gzipped. Every plugin that is enabled adds < 1 KB to that. The breakdown is as follows:60Vanilla Immer kicks in at ~3KB gzipped. Every plugin that is enabled adds ~1-2 KB to that. The breakdown is as follows:6162```63Import size report for immer:64┌───────────────────────┬───────────┬────────────┬───────────┐64│ (index) │ just this │ cumulative │ increment │65│ (index) │ just this │ cumulative │ increment │66├───────────────────────┼───────────┼────────────┼───────────┤66│ import * from 'immer' │ 5033 │ 0 │ 0 │67│ produce │ 3324 │ 3324 │ 0 │68│ enableMapSet │ 4030 │ 4039 │ 715 │69│ enablePatches │ 4112 │ 4826 │ 787 │67│ import * from 'immer' │ 6908 │ 0 │ 0 │68│ produce │ 4183 │ 4183 │ 0 │69│ enableMapSet │ 4971 │ 4980 │ 797 │70│ enablePatches │ 5335 │ 6097 │ 1117 │71│ enableArrayMethods │ 4768 │ 6659 │ 562 │72└───────────────────────┴───────────┴────────────┴───────────┘73(this report was generated by npmjs.com/package/import-size)74```75
6 unmodified lines
modified:website/docs/performance.mdx+11 added
67 unmodified lines
68- The ES5 fallback implementation is roughly twice as slow as the proxy implementation, in some cases worse.6970## Performance tips7172### Enable the Array Methods Plugin7374For applications with significant array iteration within producers, enable the [Array Methods Plugin](./array-methods.md):7576```javascript77import {enableArrayMethods} from "immer"78enableArrayMethods()79```8081This plugin optimizes array operations like `filter`, `find`, `some`, `every`, and `slice` by avoiding proxy creation for every element during iteration. Without the plugin, iterating a 1000-element array creates 1000+ proxies. With the plugin, callbacks receive base values, and proxies are only created for elements you actually mutate.8283### Pre-freeze data8485When adding a large data set to the state tree in an Immer producer (for example data received from a JSON endpoint), it is worth to call `freeze(json)` on the root of the data that is being added first. To _shallowly_ freeze it. This will allow Immer to add the new data to the tree faster, as it will avoid the need to _recursively_ scan and freeze the new data.86
11 unmodified lines
modified:website/docs/pitfalls.md+26 added
85 unmodified lines
86remove(values, a)87```8889If possible, it's recommended to perform the comparison outside the `produce` function, or to use a unique identifier property like `.id` instead, to avoid needing to use `original`.9091### Array Methods Plugin: Callbacks receive base values9293When using the [Array Methods Plugin](./array-methods.md) (`enableArrayMethods()`), callbacks for overridden methods like `filter`, `find`, `some`, `every`, and `slice` receive **base values** (not drafts). This is the core performance optimization - it avoids creating proxies for every element during iteration.9495```javascript96import {enableArrayMethods, produce} from "immer"97enableArrayMethods()9899produce(state, draft => {100 draft.items.filter(item => {101 // `item` is a base value here, NOT a draft102 // Reading works fine:103 return item.value > 10104105 // But direct mutation here won't be tracked:106 // item.value = 999 // ❌ Won't affect the draft!107 })108109 // Instead, use the returned result (which contains drafts):110 const filtered = draft.items.filter(item => item.value > 10)111 filtered[0].value = 999 // ✅ This works - filtered[0] is a draft112})113```114115This only applies to methods intercepted by the plugin. Methods like `map`, `forEach`, `reduce` are NOT overridden and work normally - their callbacks receive drafts.
modified:package.json+1 added-1 removed
36 unmodified lines
37 "coveralls": "vitest run --coverage && cat ./coverage/lcov.info | ./node_modules/.bin/coveralls && rm -rf ./coverage",38 "build": "tsup",39 "publish-docs": "cd website && GIT_USER=mweststrate USE_SSH=true yarn docusaurus deploy",40 "start": "cd website && yarn start",41 "test:size": "yarn build && yarn import-size --report . produce enableMapSet enablePatches",41 "test:size": "yarn build && yarn import-size --report . produce enableMapSet enablePatches enableArrayMethods",42 "test:sizequick": "yarn build && yarn import-size . produce"43 },44 "husky": {45 "hooks": {
52 unmodified lines