var list = [];
for (var i = 0; i < 1000 * 1000; i++) {
list.push(i);
}
list.push('slice');
list = list.slice(1);
list.push('splice');
var clone = [list];
clone.splice(0, 1);
list.push('splice');
list.shift();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
slice | |
splice | |
shift |
Test name | Executions per second |
---|---|
slice | 58.8 Ops/sec |
splice | 137.4 Ops/sec |
shift | 1355.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Definition and Purpose
The benchmark aims to compare the performance of three different approaches to manipulate an array of length 100,000:
slice
: Creates a new array by copying a subset of elements from the original array.splice
: Mutates the original array by removing or inserting elements at specific positions.shift
: Removes and returns the first element of the array.The benchmark measures which approach is the fastest to maintain a constant size of the array, while still performing the specified operation.
Options Compared
slice
vs splice
vs shift
splice
and shift
mutate the original array, whereas slice
creates a new copy.splice
can be slower due to its potential impact on the array's internal structure.shift
can be faster since it only removes the first element, which is typically less expensive than modifying an array's middle or end elements.Pros and Cons
splice
is typically faster than slice
, especially for larger arrays, since it only requires modifying the existing data structure.Library: Array.prototype.slice()
The slice()
method creates a new array by copying a subset of elements from the original array. It takes two arguments:
In this benchmark, slice
is used to create a copy of the first 99,999 elements of the array (list.slice(1)
).
Library: Array.prototype.splice()
The splice()
method modifies the original array by removing or inserting elements at specific positions. It takes two arguments:
In this benchmark, splice
is used to remove the first element from the array (clone.splice(0, 1)
).
Library: Array.prototype.shift()
The shift()
method removes and returns the first element of the array. It does not modify the original array.
In this benchmark, shift
is used to remove and return the first element of the array (list.shift()
).
Special JS Feature/ Syntax
None mentioned in this benchmark.
Alternatives
Other approaches to manipulate arrays could be considered, such as:
Array.prototype.map()
, Array.prototype.filter()
, or Array.prototypeforEach()
instead of slice
or splice
.Array.prototype.concat()
or Array.prototype.push()
to add elements to the array.However, these alternatives may not be as efficient or effective as the original approaches used in this benchmark.