Skip to content

Instantly share code, notes, and snippets.

@imogenkinsman
Last active May 8, 2022 04:49
Show Gist options
  • Save imogenkinsman/c19e52fb7173ea187d81d06b6c839205 to your computer and use it in GitHub Desktop.
Save imogenkinsman/c19e52fb7173ea187d81d06b6c839205 to your computer and use it in GitHub Desktop.
JavaScript immutable array performance

index.ts

import Immutable from 'immutable';

// this transpiles to the same thing as testJS
const testTS = (arraySize: number): void => {
  const array: readonly number[] = Array(arraySize).fill(0);

  const t0 = performance.now();

  const array2 = [...array, 4];

  const t1 = performance.now();

  console.log(``Immutable TS: ${t1 - t0}ms``);
};

const testJS = (arraySize: number): void => {
  const array = Array(arraySize).fill(0);

  const t0 = performance.now();

  const array2 = [...array, 4];

  const t1 = performance.now();

  console.log(``Vanilla JS (copy): ${t1 - t0}ms``);
};

const testJSMutation = (arraySize: number): void => {
  const array = Array(arraySize).fill(0);

  const t0 = performance.now();

  array.push(4);

  const t1 = performance.now();

  console.log(``Vanilla JS (mutation): ${t1 - t0}ms``);
};

const testImmutable = (arraySize: number): void => {
  const array = Immutable.List(Array(arraySize).fill(0));

  const t0 = performance.now();

  // push in immutable.js doesn't actually mutate; it returns a new collection
  const array2 = array.push(4);

  const t1 = performance.now();

  console.log(``Immutable.js: ${t1 - t0}ms``);
};

[1_000, 10_000, 100_000, 1_000_000].forEach((n) => {
  console.log(``n = ${n}``);
  testTS(n);
  testJS(n);
  testJSMutation(n);
  testImmutable(n);
  console.log('\n');
});

Output:

imogen@wintermute:~/test$ node src/index.js
n = 1000
Immutable TS: 0.013199985027313232ms
Vanilla JS (copy): 0.007800042629241943ms
Vanilla JS (mutation): 0.0067999958992004395ms
Immutable.js: 0.034900009632110596ms


n = 10000
Immutable TS: 0.384399950504303ms
Vanilla JS (copy): 0.31709998846054077ms
Vanilla JS (mutation): 0.007500052452087402ms
Immutable.js: 0.010399997234344482ms


n = 100000
Immutable TS: 0.7488999962806702ms
Vanilla JS (copy): 0.7429999709129333ms
Vanilla JS (mutation): 0.2712000012397766ms
Immutable.js: 0.013700008392333984ms


n = 1000000
Immutable TS: 6.018599987030029ms
Vanilla JS (copy): 4.666600048542023ms
Vanilla JS (mutation): 3.167899966239929ms
Immutable.js: 0.08640003204345703ms

Results

Immutable.js has more overhead than regular javascript arrays, so it makes sense that for any reasonably sized array it's going to be slower. With unusually large arrays, Immutable.js may be more performant.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment