var array = Array(10000).fill(0)
var itemsToRemove = 5000
array = array.slice(itemsToRemove)
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() | 712342.2 Ops/sec |
array.splice() | 6672609.5 Ops/sec |
array.shift() | 17557.0 Ops/sec |
The benchmark provided is focused on comparing the performance of three different methods for removing items from the beginning of an array in JavaScript. The methods tested are array.slice()
, array.splice()
, and array.shift()
. Each method has different characteristics, which are worth discussing for understanding their performance implications.
array.slice()
:
array = array.slice(itemsToRemove)
slice
method creates a new array containing a portion of the original array (in this case, the elements after the first itemsToRemove
elements).slice
does not modify the original array; it returns a new array.array.splice()
:
array.splice(0, itemsToRemove)
splice
method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.array.shift()
:
for (let i = 0 ; i < itemsToRemove ; i++) array.shift()
shift
method removes the first element from an array and returns that removed element. It alters the length of the array.shift
re-indexes the remaining elements. This might lead to a higher time complexity (O(n) for each call), making it inefficient when removing many items (in this case, 5000).The results of the benchmark show the number of executions per second for each method:
When to Use Each Method:
splice
when you need to modify the original array and focus on performance.slice
for cases where you need to maintain the original array and avoid side effects.shift
for large scale removals from the beginning of an array due to performance constraints.Other Alternatives:
In summary, while testing array manipulations, understanding the underlying operations and efficiency trade-offs can guide engineers in choosing the right approach for their specific use cases. The benchmark illustrates clear distinctions in performance, which can inform decisions in real-world applications.