var array = [1, 2, 3, 4, 5, 6, 7, 8]
var itemsToRemove = 5
for (let i = 0 ; i < itemsToRemove ; i++) array = array.slice(1)
for (let i = 0 ; i < itemsToRemove ; i++) array.splice(0, 1)
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() | 1587958.4 Ops/sec |
array.splice() | 2284566.0 Ops/sec |
array.shift() | 2556044.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition
The benchmark defines three test cases:
array.slice(1)
.array.splice(0, 1)
.array.shift()
.Options Compared
The benchmark compares three different approaches to remove 2 items from the beginning of an array:
array.slice(1)
: Creates a new array by copying all elements except the first two.array.splice(0, 1)
: Modifies the original array by removing the first element and shifting the remaining elements one position forward.array.shift()
: Removes the first element from the array.Pros and Cons of Each Approach
array.slice(1)
: Pros:array.splice(0, 1)
: Pros:array.shift()
: Pros:Other Considerations
The benchmark does not take into account other factors that could affect performance, such as:
for
loops to iterate over the removal process.Library and Special JS Features
There are no libraries mentioned in the provided code. However, if you're interested in testing other libraries or special JavaScript features, MeasureThat.net also supports:
Lodash
or Ramda
.async/await
, let const
, or class/instance
.Alternatives
If you're looking for alternative benchmarking tools for your JavaScript code, consider the following options: