var list = [];
for (var i = 0; i < 1000 * 1000; i++) {
list.push(i);
}
list.push('slice');
list = list.slice(50);
list.push('splice');
list.splice(0, 50);
list.push('splice');
for (let i = 0; i<50; i++) {
list.shift();
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
slice | |
splice | |
shift |
Test name | Executions per second |
---|---|
slice | 197.6 Ops/sec |
splice | 224476.7 Ops/sec |
shift | 304759.2 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
What is being tested?
The provided JSON represents a benchmark that tests three different methods for modifying an array:
slice
: creates a new array containing a subset of elements from the original array using the Array.prototype.slice()
method.splice
: modifies the original array by removing or replacing elements at specific indices using the Array.prototype.splice()
method.shift
: removes elements from the beginning of the array using the Array.prototype.shift()
method.These tests are designed to measure the performance differences between these three methods for various sizes of arrays.
Options compared
The benchmark compares the execution time of each method:
slice
: creates a new array and copies a subset of elements from the original array.splice
: modifies the original array in place, which can be faster but also more memory-intensive.shift
: removes elements from the beginning of the array without creating a new array.Pros and cons
Here's a brief summary of the pros and cons of each method:
Library and syntax considerations
In this benchmark, there are no libraries or external dependencies required. The tests are self-contained JavaScript code that runs directly in the browser.
However, it's worth noting that the slice()
method was introduced in ECMAScript 5 (ES5), which is supported by most modern browsers. The splice()
and shift()
methods have been part of the language since its inception.
Other alternatives
For larger array sizes or more complex data structures, other methods might be more suitable:
Array.prototype.subarray()
or Array.prototype.copyWithin()
instead of slice()
could provide better performance.splice()
is often a good choice. However, if the number of operations is high, using an array-based data structure like a linked list might be more efficient.In summary, this benchmark provides a straightforward comparison between three common array modification methods in JavaScript: slice
, splice
, and shift
. The results can help developers understand the trade-offs involved in choosing these methods for their specific use cases.