Skip to content

Instantly share code, notes, and snippets.

@Aschen
Last active April 12, 2022 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aschen/0ed940f64387405c8772c4bbff2299d0 to your computer and use it in GitHub Desktop.
Save Aschen/0ed940f64387405c8772c4bbff2299d0 to your computer and use it in GitHub Desktop.
Benchmark mutable vs immutable for objects and arrays

Immutability has a cost, here is how much

object - vanilla immutable x 903,841 ops/sec ±5.33% (77 runs sampled)
object - immutable.js    x 1,672,774 ops/sec ±1.68% (89 runs sampled)
object - mutable       x 546,235,424 ops/sec ±0.84% (83 runs sampled)

array - vanilla immutable x 4,855,761 ops/sec ±1.55% (91 runs sampled)
array - immutable.js        x 618,146 ops/sec ±3.56% (85 runs sampled)
array - mutable           x 9,849,954 ops/sec ±4.00% (85 runs sampled)

Original article: https://aschen.tech/index.php/2022/04/12/le-cout-de-limmutabilite/

const { Map, List } = require('immutable');
const {Benchmark} = require('benchmark');
var suite = new Benchmark.Suite;
function objectsManipulation (suite) {
return suite
.add('object - vanilla immutable', function() {
let person = { name: 'Aschen', age: 28 };
// add property
person = { ...person, city: 'ahangama' };
// update property
person = { ...person, age: 42 };
})
.add('object - immutable.js', function() {
let person = new Map({ name: 'aschen', age: 28 });
// add property
person = person.set('city', 'ahangama');
// set property
person = person.set('age', 42);
})
.add('object - mutable', function() {
let person = { name: 'Aschen', age: 28 };
// add property
person.city = 'ahangama';
// update property
person.age = 42;
});
}
function arraysManipulation (suite) {
return suite
.add('array - vanilla immutable', function() {
let cities = ['tirana', 'montpellier', 'minsk', 'tbilisi', 'ahangama'];
// push city
cities = [...cities, 'adrasan'];
// remove city "minsk"
cities = [...cities.slice(0, 2), ...cities.slice(3)];
})
.add('array - immutable.js', function() {
let cities = new List(['tirana', 'montpellier', 'minsk', 'tbilisi', 'ahangama']);
// push city
cities = cities.push('adrasan');
// remove city "minsk"
cities = cities.delete(2);
})
.add('array - mutable', function() {
let cities = ['tirana', 'montpellier', 'minsk', 'tbilisi', 'ahangama'];
// push city
cities.push('adrasan');
// remove city "minsk"
cities.splice(2);
});
}
// add tests
objectsManipulation(suite)
arraysManipulation(suite)
// add listeners
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment