var list = [];
for (var i = 0; i < 1000 * 1000; i++) {
list.push(i);
}
list.push(Array(11))
list = list.slice(-11);
list.push(Array(11))
list = list.splice(-11);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
1 | |
2 |
Test name | Executions per second |
---|---|
1 | 4398360.0 Ops/sec |
2 | 4295135.5 Ops/sec |
I'd be happy to explain the benchmark and its different approaches.
Overview of the Benchmark
The benchmark is designed to compare two approaches for removing the last 11 elements from an array in JavaScript: slice()
and splice()
. The test creates a large array with 1 million elements, pushes 11 more elements into it, and then measures which approach is faster.
Approach 1: Using Array.prototype.slice()
The first benchmark definition uses Array.prototype.slice()
to remove the last 11 elements from the array:
list.push(...Array(11))
list = list.slice(-11)
This approach creates a new array slice containing the last 11 elements, and then assigns it back to the original array. The pros of this approach are:
However, the cons are:
Approach 2: Using Array.prototype.splice()
The second benchmark definition uses Array.prototype.splice()
to remove the last 11 elements from the array:
list.push(...Array(11))
list = list.splice(-11)
This approach modifies the original array in place, removing the last 11 elements. The pros of this approach are:
However, the cons are:
splice()
can be less predictable than slice()
, as it modifies the array and returns an array slice.Library Used: None
There is no library used in this benchmark. Both approaches are built-in methods of the JavaScript Array prototype.
Special JS Feature/ Syntax: None
This benchmark does not use any special JavaScript features or syntax, such as async/await or decorators.
Other Alternatives
If you want to remove the last N elements from an array without using slice()
or splice()
, there are other alternatives:
Array.prototype.reduce()
: You can use reduce()
to build a new array with the desired length, like this: list = list.reduce((acc, curr) => acc.length < 11 ? [...acc, curr] : acc.slice(0, -11), [])
.Array.prototype.filter()
: You can use filter()
to create a new array with only the elements you want, like this: list = list.filter((_, i) => i >= 11)
.Keep in mind that these alternatives may have different performance characteristics than slice()
and splice()
.