<script
src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"
crossorigin="anonymous"></script>
var obj = { b:"hello", c: true, d:7 };
var arr = ['a', 'b', 'c'];
var map = Immutable.Map(obj);
var list = Immutable.List(arr);
var newVal = { obj, b: 'world' };
var newVal = map.set('b', 'world');
var newVal = [ arr, 'd' ];
var newVal = list.push('d');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object set - spread | |
Object set - immutable | |
Array push - spread | |
Array push - immutable |
Test name | Executions per second |
---|---|
Object set - spread | 12526865.0 Ops/sec |
Object set - immutable | 4947420.0 Ops/sec |
Array push - spread | 15413141.0 Ops/sec |
Array push - immutable | 3575624.8 Ops/sec |
Let's break down the benchmark and explain what is being tested, compared, and its pros and cons.
Benchmark Overview
The benchmark measures the performance of two approaches: using the spread operator (...
) to create a new object or array, and using Immutable.js, a library that provides immutable data structures in JavaScript. The benchmark compares the performance of these two approaches for common use cases:
Options Compared
The two options being compared are:
...
): This approach uses the spread operator to create a new object or array by copying the properties of an existing object or array.set()
, push()
, etc., to modify them.Pros and Cons
...
):Library and Its Purpose
Map
, List
) and utility functions (e.g., set()
, push()
) that allow you to work with data in a predictable and consistent way. Immutable.js is designed to help developers write more robust and maintainable code.Special JavaScript Feature or Syntax
There is no special JavaScript feature or syntax being used in this benchmark, except for the use of ES6 spread operator (...
).
Other Alternatives
If you're looking for alternative approaches, you could consider using:
slice()
to create a shallow copy of an array and then concatenate the new element using concat()
. However, this approach is slower than the spread operator.Keep in mind that the best approach will depend on your specific use case and requirements. If you need predictable performance and are willing to learn a new library, Immutable.js might be a good choice. Otherwise, the spread operator could be sufficient for most use cases.