<script src="https://unpkg.com/immutable@4.0.0-rc.12/dist/immutable.min.js"></script>
let initArr = new Array(5000).fill(88);
const limitArr = (arr, limit) => (arr.length > limit ? arr.slice(-limit) : arr);
for(i=0; i<10000; i++) {
initArr.push(55, 12, 3);
initArr = limitArr(initArr, 5000);
}
let initList = Immutable.List();
initList = initList.push( (new Array(5000).fill(88)));
const limitList = (list, limit) => (list.size > limit ? list.takeLast(limit) : list);
for(i=0; i<10000; i++) {
initList = limitList(initList.push(55, 12, 3), 5000);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array slice | |
immutable-js |
Test name | Executions per second |
---|---|
array slice | 11.7 Ops/sec |
immutable-js | 123.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks and analyze the provided benchmark.
Overview
The provided benchmark compares two approaches for limiting the length of an array:
Array.prototype.slice()
What is tested?
The benchmark tests the performance of these two approaches in different scenarios:
array slice
, 55,000 elements are pushed onto an array with an initial size of 5,000. The slice()
method is then used to limit the array length to 5,000.immutable-js
, an Immutable.js list is created and populated with 55,000 elements. The takeLast()
method is then used to limit the list size to 5,000.Options compared
The benchmark compares two options:
Array.prototype.slice()
: A built-in JavaScript method for limiting the length of an array.Pros and Cons
Here are some pros and cons of each approach:
Array.prototype.slice()
Pros:
Cons:
Immutable.js
Pros:
Cons:
Library: Immutable.js
Immutable.js is a popular JavaScript library for working with immutable data structures. It provides a range of methods for creating, manipulating, and transforming immutable data structures, such as lists, sets, maps, and more.
In this benchmark, Immutable.js is used to create an Immutable.js list and then apply the takeLast()
method to limit its size.
Special JS feature: No
There are no special JavaScript features or syntaxes involved in these test cases. The focus is on comparing the performance of different array manipulation approaches.
Other alternatives
If you're looking for alternative approaches to array manipulation, here are a few options:
Array.prototype.splice()
: This method can be used to remove elements from an array and limit its size.Array.prototype.slice().concat()
: This approach involves creating a new array by slicing the original array and then concatenating it with a new array containing only the desired elements.Keep in mind that each of these alternatives has its own trade-offs and performance characteristics, and may not offer the same level of predictability and reliability as Immutable.js or Array.prototype.slice()
.