Skip to content
Myr

fix: preserve structural sharing for no-op array-methods calls

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

The enableArrayMethods() plugin routed every mutating array method through executeArrayMethod, which unconditionally called markChanged. As a result calls that change nothing - push()/unshift() with no arguments (e.g. the common draft.list.push(...items) with an empty items), splice(i, 0), and pop()/shift() on an empty array - produced a new state reference, breaking the structural-sharing guarantee that native Immer keeps (produce returning the base when nothing changed). Detect these no-ops in O(1) and skip marking the array changed, so the producer returns the base and emits no patches, matching core behavior.

authored by maximilliangrand · committed by maximilliangrand · parent d2c158f · Browse files · 2 files+88 added−16 removed
This commit

State

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

Trailers

  • Signed-off-by: maximilliangrand <214999687+maximilliangrand@users.noreply.github.com>

Diff stats

2 files+88 added−16 removed

  • tests:+38 added−0 removed
  • other:+50 added−16 removed

2 files+88 added−16 removed

modified:__tests__/base.js+38 added
290 unmodified lines
291 expect(nextState.anArray.length).toBe(baseLength + 1)292 })293294 describe("mutating array methods", () => {295 describe("no-op calls preserve structural sharing", () => {296 it("push() with no arguments returns the base", () => {297 const base = {list: [1, 2, 3], keep: {x: 1}}298 const [next, patches] = produceWithPatches(base, d => {299 d.list.push(...[])300 })301 expect(next).toBe(base)302 expect(next.keep).toBe(base.keep)303 expect(patches).toHaveLength(0)304 })305306 it("unshift() with no arguments returns the base", () => {307 const base = {list: [1, 2, 3]}308 const next = produce(base, d => {309 d.list.unshift()310 })311 expect(next).toBe(base)312 })313314 it("splice() that removes and inserts nothing returns the base", () => {315 const base = {list: [1, 2, 3]}316 const [next, patches] = produceWithPatches(base, d => {317 d.list.splice(1, 0)318 })319 expect(next).toBe(base)320 expect(patches).toHaveLength(0)321 })322323 it("pop()/shift() on an empty array return the base", () => {324 const base = {popped: [], shifted: []}325 const next = produce(base, d => {326 d.popped.pop()327 d.shifted.shift()328 })329 expect(next).toBe(base)330 })331 })332333 // Reported here: https://github.com/mweststrate/immer/issues/116334 it("can pop then push", () => {335 const nextState = produce([1, 2, 3], s => {336 s.pop()
3931 unmodified lines
modified:src/plugins/arrayMethods.ts+50 added-16 removed
172 unmodified lines
173 markLength = true174 ): T {175 prepareCopy(state)176 const result = operation()177 markArrayChanged(state, markLength)178 return result179 }180181 /**182 * Marks the array (and its ancestors) as modified after a mutating operation.183 *184 * Kept separate from `executeArrayMethod` so that operations which turn out to185 * be no-ops (e.g. `push()` with no arguments, `splice(i, 0)`, `pop()`/`shift()`186 * on an empty array) can prepare a copy but skip marking, preserving Immer's187 * structural-sharing guarantee that a change-free producer returns the base.188 */189 function markArrayChanged(state: ProxyArrayState, markLength = true) {190 markChanged(state)191 if (markLength) state.assigned_!.set("length", true)179 return result192 }193194 function markAllIndicesReassigned(state: ProxyArrayState) {195 state.allIndicesReassigned_ = true
49 unmodified lines
245 state: ProxyArrayState,246 method: string,247 args: any[]248 ) {237 return executeArrayMethod(state, () => {238 // For push/unshift, capture the length before the operation239 // so we can compute insertion indices for handleCrossReference240 const lengthBefore = state.copy_!.length249 prepareCopy(state)250242 const result = (state.copy_! as any)[method](...args)251 // For push/unshift, capture the length before the operation252 // so we can compute insertion indices for handleCrossReference253 const lengthBefore = state.copy_!.length254255 const result = (state.copy_! as any)[method](...args)256257 // Detect no-op calls so structural sharing is preserved:258 // push/unshift with no arguments add nothing, and pop/shift on an259 // empty array remove nothing. In those cases the array is unchanged.260 const changed =261 method === "push" || method === "unshift"262 ? args.length > 0263 : lengthBefore > 0 // pop / shift264265 if (changed) {266 markArrayChanged(state)267268 // Handle index reassignment for shifting methods269 if (SHIFTING_METHODS.has(method as MutatingArrayMethod)) {270 markAllIndicesReassigned(state)271 }272273 // Handle cross-references for newly inserted values.274 // push appends at the end, unshift inserts at the beginning.251 if (method === "push" && args.length > 0) {275 if (method === "push") {276 handleInsertedValues(state, lengthBefore, args)253 } else if (method === "unshift" && args.length > 0) {277 } else if (method === "unshift") {278 handleInsertedValues(state, 0, args)279 }280 }281257 // Return appropriate value based on method258 return RESULT_RETURNING_METHODS.has(method as MutatingArrayMethod)259 ? result260 : state.draft_261 })282 // Return appropriate value based on method283 return RESULT_RETURNING_METHODS.has(method as MutatingArrayMethod)284 ? result285 : state.draft_286 }287288 /**289 * Handles reordering operations (reverse, sort) that change element order.
57 unmodified lines
347 return handleReorderingOperation(state, method, args)348 }349350 if (method === "splice") {327 const res = executeArrayMethod(state, () =>328 state.copy_!.splice(...(args as [number, number, ...any[]]))351 prepareCopy(state)352 const insertCount = args.length > 2 ? args.length - 2 : 0353 const res = state.copy_!.splice(354 ...(args as [number, number, ...any[]])355 )356357 // A splice that removes and inserts nothing leaves the array358 // unchanged, so structural sharing must be preserved.359 if (res.length === 0 && insertCount === 0) {360 return res361 }362363 markArrayChanged(state)364 markAllIndicesReassigned(state)365 // Handle cross-references for inserted values (args from index 2+)332 if (args.length > 2) {366 if (insertCount > 0) {367 const startIndex = normalizeSliceIndex(368 args[0] ?? 0,369 state.copy_!.length370 )
110 unmodified lines