<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>
const list = Immutable.List();
let resultArray = [];
for (var i = 0; i < 100; i++) {
list.push(i);
}
resultArray = list.toArray();
resultArray = list.toJS();
list.map(i => resultArray.push(i))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
toArray | |
toJS | |
map + push |
Test name | Executions per second |
---|---|
toArray | 8800802.0 Ops/sec |
toJS | 7280229.5 Ops/sec |
map + push | 34065820.0 Ops/sec |
In the provided benchmark, the performance of different methods provided by the Immutable.js library is tested. Immutable.js is a library that helps manage data structures in an immutable way, meaning that once data structures are created, they cannot be changed. This can lead to optimizations in performance, especially in applications where data changes frequently.
toArray():
toJS():
toArray()
, it incurs the overhead of a full conversion, and if the collection is complex (like deeply nested objects), this may become inefficient.map + push:
map
function on the Immutable.js List, and for each element, it pushes that element into a regular JavaScript array.push
method, and it still involves iterating over the list elements, which may end up being slower than a direct conversion depending on implementation.The benchmark results show the number of executions per second for each method on a specific environment (Chrome 133 on Mac OS X 10.15.7):
From these numbers, it is clear that map + push
significantly outperforms the other two methods in terms of execution speed. This could be due to optimizations within how the method is executed in the JavaScript engine.
toArray()
might suffice. However, if processing is necessary, map + push
may be more beneficial despite the potential for added complexity in the implementation.toArray()
and toJS()
) may temporarily require more memory if large datasets are created.Apart from the methods tested in the benchmark, one may also consider:
forEach()
for manual construction could provide better control over the transformation logic.Lodash
or the native JavaScript features can provide alternatives for data manipulation without introducing the overhead of immutability.In conclusion, while the benchmark clearly shows the performance of different Immutable.js collection handling methods, the selection of the appropriate method should weigh factors like performance, their specific use cases, and future maintainability of the code.