Mutative

Efficient immutable updates, 10x faster than Immer by default, even faster ...

README

Mutative


Node CI
Coverage Status
npm
license

Mutative - A JavaScript library for efficient immutable updates, 10x faster than Immer by default, even faster than naive handcrafted reducer.

Benchmark

Motivation


Writing immutable updates by hand is usually difficult, prone to errors and cumbersome. Immer helps us write simpler immutable updates with "mutative" logic.

But its performance issue causes a runtime performance overhead. Immer must have auto-freeze enabled by default(Performance will be worse if auto-freeze is disabled), such immutable state with Immer are not common. In scenarios such as cross-process, remote data transfer, etc., we have to constantly freeze these immutable data.

There are more parts that could be improved, such as better type inference, non-intrusive markup, support for more types of immutability, Safer immutability, and so on.

This is why Mutative was created.

Mutative vs Immer Performance


Measure(ops/sec) to update 50K arrays and 1K objects, bigger the better(view source).

  1. ```
  2. Naive handcrafted reducer - No Freeze x 3,713 ops/sec ±0.86% (89 runs sampled)
  3. Mutative - No Freeze x 5,323 ops/sec ±1.69% (93 runs sampled)
  4. Immer - No Freeze x 8 ops/sec ±0.88% (23 runs sampled)

  5. Mutative - Freeze x 875 ops/sec ±1.20% (95 runs sampled)
  6. Immer - Freeze x 320 ops/sec ±0.45% (92 runs sampled)

  7. Mutative - Patches and No Freeze x 752 ops/sec ±0.16% (96 runs sampled)
  8. Immer - Patches and No Freeze x 7 ops/sec ±1.32% (23 runs sampled)

  9. Mutative - Patches and Freeze x 425 ops/sec ±0.33% (95 runs sampled)
  10. Immer - Patches and Freeze x 239 ops/sec ±0.99% (89 runs sampled)

  11. The fastest method is Mutative - No Freeze
  12. ```

Run yarn benchmark to reproduce them locally.

OS: macOS 12.6, CPU: Apple M1 Max, Node.js: 16.14.2


Immer relies on auto-freeze to be enabled, if auto-freeze is disabled, Immer will have a huge performance drop and Mutative will have a huge performance lead, especially with large data structures it will have a performance lead of more than 50x.

So if you are using Immer, you will have to enable auto-freeze for performance. Mutative allows to disable auto-freeze by default. With the default configuration of both, we can see the performance gap between Mutative (5,323 ops/sec) and Immer (320 ops/sec).

Overall, Mutative has a huge performance lead over Immer in more performance testing scenarios. Runyarn performance to get all the performance results locally.

Features and Benefits


- Mutation makes immutable updates
- Support apply patches
- Optional freezing state
- Custom shallow copy
- Immutable and mutable data markable
- Strict mode for safer mutable data access
- Support for JSON patches

Mutative Size: 4.11 kB with all dependencies, minified and gzipped.


Difference between Mutative and Immer


| -                         | Mutative | Immer |
| :------------------------ | -------: | :---: |
| Custom shallow copy       |       ✅ |  ❌   |
| Strict mode               |       ✅ |  ❌   |
| No data freeze by default |       ✅ |  ❌   |
| Non-invasive marking      |       ✅ |  ❌   |
| Complete freeze data      |       ✅ |  ❌   |
| Non-global config         |       ✅ |  ❌   |
| Support IE browser        |       ❌ |  ✅   |

Mutative draft functions don't allow return value (except for void or Promise<void>), but Immer is allowed.


Mutative has fewer bugs such as accidental draft escapes than Immer, view details.

Installation


  1. ```sh
  2. yarn install mutative # npm install mutative
  3. ```

Usage


  1. ```ts
  2. import { create } from 'mutative';

  3. const baseState = {
  4.   foo: 'bar',
  5.   list: [{ text: 'coding' }],
  6. };

  7. const state = create(baseState, (draft) => {
  8.   draft.foo = 'foobar';
  9.   draft.list.push({ text: 'learning' });
  10. });
  11. ```

create(baseState, (draft) => void, options?: Options): newState

The first argument of create() is the base state. Mutative drafts it and passes it to the arguments of the draft function, and performs the draft mutation until the draft function finishes, then Mutative will finalize it and produce the new state.

Use create() for more advanced functions by setting options.

APIs


create()


Use create() for draft mutation to get a new state, which also supports currying.

  1. ```ts
  2. import { create } from 'mutative';

  3. const baseState = {
  4.   foo: 'bar',
  5.   list: [{ text: 'todo' }],
  6. };

  7. const state = create(baseState, (draft) => {
  8.   draft.foo = 'foobar';
  9.   draft.list.push({ text: 'learning' });
  10. });
  11. ```

In this basic example, the changes to the draft are 'mutative' within the draft callback, and create() is finally executed with a new immutable state.

create(state, fn, options) - Then options is optional.


- strict - boolean, the default is false.

  > Forbid accessing non-draftable values in strict mode(unless using unsafe()).

- enablePatches - boolean, the default is false.

  > Enable patch, and return the patches and inversePatches.

- enableAutoFreeze - boolean, the default is false.

  > Enable autoFreeze, and return frozen state.

- mark - () => ('mutable'|'immutable'|function)
  > Set a mark to determine if the object is mutable or if an instance is an immutable, and it can also return a shallow copy function(AutoFreeze and Patches should both be disabled).

create() - Currying


- create draft

  1. ```ts
  2. const [draft, finalize] = create(baseState);
  3. draft.foobar.bar = 'baz';
  4. const state = finalize();
  5. ```

- create producer

  1. ```ts
  2. const producer = create(() => {
  3.   draft.foobar.bar = 'baz';
  4. });
  5. const state = producer(baseState);
  6. ```

They also all support set options such as const [draft, finalize] = create(baseState, { enableAutoFreeze: true });


apply()


Use apply() for patches to get the new state.

  1. ```ts
  2. import { create, apply } from 'mutative';

  3. const baseState = {
  4.   foo: 'bar',
  5.   list: [{ text: 'todo' }],
  6. };

  7. const [state, patches, inversePatches] = create(
  8.   baseState,
  9.   (draft) => {
  10.     draft.foo = 'foobar';
  11.     draft.list.push({ text: 'learning' });
  12.   },
  13.   {
  14.     enablePatches: true,
  15.   }
  16. );

  17. const nextState = apply(baseState, patches);
  18. expect(nextState).toEqual(state);
  19. const prevState = apply(state, inversePatches);
  20. expect(prevState).toEqual(baseState);
  21. ```

current()


Get the current value in the draft.

  1. ```ts
  2. const baseState = {
  3.   foo: 'bar',
  4.   list: [{ text: 'todo' }],
  5. };

  6. const state = create(baseState, (draft) => {
  7.   draft.foo = 'foobar';
  8.   draft.list.push({ text: 'learning' });
  9.   expect(current(draft.list)).toEqual([{ text: 'todo' }, { text: 'learning' }]);
  10. });
  11. ```

original()


Get the original value in the draft.

  1. ```ts
  2. const baseState = {
  3.   foo: 'bar',
  4.   list: [{ text: 'todo' }],
  5. };

  6. const state = create(baseState, (draft) => {
  7.   draft.foo = 'foobar';
  8.   draft.list.push({ text: 'learning' });
  9.   expect(original(draft.list)).toEqual([{ text: 'todo' }]);
  10. });
  11. ```

unsafe()


When strict mode is enabled, mutable data can only be accessed using unsafe().

  1. ```ts
  2. const baseState = {
  3.   list: [],
  4.   date: new Date(),
  5. };

  6. const state = create(
  7.   baseState,
  8.   (draft) => {
  9.     unsafe(() => {
  10.       draft.date.setFullYear(2000);
  11.     });
  12.   },
  13.   {
  14.     strict: true,
  15.   }
  16. );
  17. ```

isDraft()


Check if it is a draft.

  1. ```ts
  2. const baseState = {
  3.   date: new Date(),
  4.   list: [{ text: 'todo' }],
  5. };

  6. const state = create(baseState, (draft) => {
  7.   expect(isDraft(draft.date)).toBeFalsy();
  8.   expect(isDraft(draft.list)).toBeTruthy();
  9. });
  10. ```

Using TypeScript


- castDraft()
- castImmutable()
- `Mutable`- `Immutable`
- Patches
- Patch
- `Options`

Integration with React



FAQs


- Why doesn't Mutative support IE?

Mutative is a library that relies heavily on the use of the Proxy object, which is a feature of modern web browsers that allows the interception of various operations on objects. As such, Mutative may not be fully compatible with older browsers that do not support the Proxy object, such as Internet Explorer. However, these older browsers make up a very small percentage of the overall browser market, so the impact on compatibility is likely minimal.

- Why does Mutative have such good performance?

Mutative optimization focus is on shallow copy optimization, more complete lazy drafts, finalization process optimization, and more.

- I'm already using Immer, can I migrate smoothly to Mutative?

Yes. Unless you have to be compatible with Internet Explorer, Mutative supports almost all of Immer features, and you can easily migrate from Immer to Mutative.

Migration is also not possible for React Native that does not support Proxy. React Native uses a new JS engine during refactoring - Hermes, and it (if < v0.59 or when using the Hermes engine on React Native < v0.64) does not support Proxy on Android, but React Native v0.64 with the Hermes engine support Proxy.


- Why return values are not supported?

If it is supported, there is an additional performance loss of traversing the returned object tree. Also Immer has draft escape issues for return values.

- Can Mutative be integrated with Redux?

Yes.

Migration from Immer to Mutative


1. produce() -> create()

Mutative auto freezing option is disabled by default, Immer auto freezing option is enabled by default (if disabled, Immer performance will have a more huge drop).

You need to check if auto freezing has any impact on your project. If it depends on auto freezing, you can enable it yourself in Mutative.


  1. ```ts
  2. import produce from 'immer';

  3. const nextState = produce(baseState, (draft) => {
  4.   draft[1].done = true;
  5.   draft.push({ title: 'something' });
  6. });
  7. ```

Use Mutative

  1. ```ts
  2. import { create } from 'mutative';

  3. const nextState = create(baseState, (draft) => {
  4.   draft[1].done = true;
  5.   draft.push({ title: 'something' });
  6. });
  7. ```

2. Patches

  1. ```ts
  2. import { produceWithPatches, applyPatches } from 'immer';

  3. enablePatches();

  4. const baseState = {
  5.   age: 33,
  6. };

  7. const [nextState, patches, inversePatches] = produceWithPatches(
  8.   baseState,
  9.   (draft) => {
  10.     draft.age++;
  11.   }
  12. );

  13. const state = applyPatches(nextState, inversePatches);

  14. expect(state).toEqual(baseState);
  15. ```

Use Mutative

  1. ```ts
  2. import { create, apply } from 'mutative';

  3. const baseState = {
  4.   age: 33,
  5. };

  6. const [nextState, patches, inversePatches] = create(
  7.   baseState,
  8.   (draft) => {
  9.     draft.age++;
  10.   },
  11.   {
  12.     enablePatches: true,
  13.   }
  14. );

  15. const state = apply(nextState, inversePatches);

  16. expect(state).toEqual(baseState);
  17. ```

TBD