var array = Array(3000).fill(0)
var itemsToRemove = 1000
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() | 6254837.0 Ops/sec |
array.splice() | 33268630.0 Ops/sec |
array.shift() | 125981.1 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Overview
The benchmark compares the performance of three methods to remove 2 items from the beginning of an array:
array.slice(2)
array.splice(0, 1000)
(removes 1000 elements)for (let i = 0; i < 1000; i++) array.shift()
(shifts 1000 elements)Library and Purpose
The benchmark uses the Array
prototype method for all three tests, which is a built-in JavaScript library.
Special JS Features and Syntax
None of the test cases use any special JavaScript features or syntax. The focus is on comparing the performance of basic array manipulation methods.
Comparison of Methods
array.slice(2)
: This method creates a new array with elements from index 2 to the end of the original array. It has a time complexity of O(n), where n is the length of the array.array.splice(0, 1000)
: This method removes elements from the beginning of the array and returns them as an array. It has a time complexity of O(n), where n is the length of the removed elements (in this case, 1000).for (let i = 0; i < 1000; i++) array.shift()
: This method uses a loop to shift elements from the beginning of the array. It has a time complexity of O(n), where n is the number of elements shifted.splice
for large arrays, as it involves multiple loop iterations.Benchmark Results
The latest benchmark results show that:
array.splice(0, 1000)
is the fastest method, with an average execution time of around 107,759,000 executions per second.array.slice(2)
is slower, with an average execution time of around 118,810,860 executions per second.for (let i = 0; i < 1000; i++) array.shift()
is the slowest method, with an average execution time of around 13,587 executions per second.Alternatives
Other alternatives to these methods include:
Array.prototype.slice.call()
or Array.prototype.splice.call()
to avoid creating new objects.Keep in mind that the performance differences between these methods can be significant, and the choice of method depends on the specific use case and requirements.