var list = [];
for (var i = 0; i < 1000 * 1000; i++) {
list.push(i);
}
list.push('slice');
list = list.slice(100);
list.push('splice');
list.splice(0, 100);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
slice | |
splice |
Test name | Executions per second |
---|---|
slice | 513.4 Ops/sec |
splice | 6807243.5 Ops/sec |
I'd be happy to explain the benchmark.
Benchmark Overview
The benchmark measures the performance of two JavaScript methods: slice
and splice
. The goal is to determine which method is faster when removing 100 elements from an array, while keeping its original size constant. In other words, we're trying to find out whether creating a copy of the array using slice
or modifying the original array using splice
(or shifting elements) is more efficient.
Options Compared
There are two methods being compared:
list.slice(100)
): This method creates a new array that includes all elements from the original array, up to the 100th element. The rest of the elements are discarded.list.splice(0, 100)
): This method modifies the original array by removing the first 100 elements.Pros and Cons
slice
):splice
due to the overhead of creating a new array.splice
):Library and Features
There are no libraries used in this benchmark. The only JavaScript features mentioned are slice
and splice
, which are built-in methods for manipulating arrays.
Special JS Feature/Syntax
There is no special JavaScript feature or syntax used in this benchmark. It's a straightforward comparison of two basic array manipulation methods.
Alternatives
If you're looking for alternative approaches, consider the following:
slice
or splice
, you could use forEach()
to iterate over the array elements, skipping every 100th element.Keep in mind that these alternatives may have additional overhead or complexity compared to simply using slice
or splice
.