var array = [1, 2, 3, 4, 5, 6, 7, 8]
var itemsToRemove = 2
array = array.slice(2)
array.splice(0, itemsToRemove)
for (let i = 0 ; i < itemsToRemove ; i++) array.shift()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array.slice() | |
array.splice() | |
array.shift() |
Test name | Executions per second |
---|---|
array.slice() | 42302956.0 Ops/sec |
array.splice() | 30252778.0 Ops/sec |
array.shift() | 67092084.0 Ops/sec |
This benchmark tests the performance of three different methods for removing the first two elements from an array in JavaScript:
array.slice(2)
: This method creates a new array containing all elements from index 2 (the third element) to the end of the original array, effectively discarding the first two elements.
array.splice(0, itemsToRemove)
: This method modifies the original array directly by removing itemsToRemove
(in this case, 2) elements starting at index 0 (the beginning).
for (let i = 0 ; i < itemsToRemove ; i++) array.shift()
: This method uses a loop to call the array.shift()
method repeatedly. array.shift()
removes and returns the first element of an array, modifying the original array.
Pros and Cons:
slice()
:
splice()
:
slice()
for simple removal operations like this one.shift()
Loop:
splice()
. Can be slower for removing only a few elements because of the loop overhead.Considerations:
The best method depends on your specific needs:
slice()
.splice()
is generally efficient. shift()
might be slightly faster.Alternatives:
While this benchmark focuses on these three methods, other approaches exist for removing array elements:
array.forEach()
and manually updating indices: This involves iterating through the array and shifting elements to fill the gaps created by removed elements. It can be complex to implement correctly but offers fine-grained control over the process.