var arr = Array.from(Array(10000), (val, index) => index);
arr.unshift(42)
arr.push(42)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
.unshift() | |
.push() |
Test name | Executions per second |
---|---|
.unshift() | 39231.8 Ops/sec |
.push() | 11287872.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
What is tested?
The provided benchmark tests two different methods for adding elements to an array: arr.unshift(42)
and arr.push(42)
. The goal is to compare their performance in a controlled environment.
Options compared:
There are only two options being compared:
arr.unshift(42)
: This method adds the element at the beginning of the array.arr.push(42)
: This method adds the element at the end of the array.Pros and Cons:
arr.unshift(42)
: This method is generally faster than push()
because it only needs to shift elements from the current end of the array, reducing the number of operations required. However, it modifies the array in place, which might be less efficient for large arrays if the array needs to be preserved.arr.push(42)
: This method is often considered more intuitive and easier to use than unshift()
, especially when adding elements at the end of an array. It's also a good choice when you want to preserve the original array.Library and syntax:
There is no external library used in this benchmark, so it relies solely on built-in JavaScript functionality. There are no special JS features or syntax being tested in this case.
Alternative approaches:
Other alternatives for adding elements to an array might include:
Array.prototype.concat()
: You could use concat()
with the element you want to add as an argument, like so: arr = arr.concat([42])
. However, this method is generally slower and more memory-intensive than push()
.Array.prototype.splice()
: This method would also work for adding elements at the end of the array, but it's typically less efficient due to its use of multiple operations (insertion at a specific index).Benchmark preparation code:
The provided Script Preparation Code
is used to create an array with 10,000 elements, each initialized with its index value. This allows for a fair comparison between the different methods being tested.
Here's how the script works:
var arr = Array.from(Array(10000), (val, index) => index);
In this code snippet:
Array.from()
is used to create an array with elements initialized by a callback function.(val, index) => index
defines the value for each element in the new array. The callback function receives two parameters: the current element from the outer array (val
) and its index in that array (index
).