var array = [1,2,3];
array.unshift(0);
array = array.concat([0])
array = [0, array]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
arrayUnshift123 | |
arrayConcat123 | |
arraySpread123 |
Test name | Executions per second |
---|---|
arrayUnshift123 | 35891.1 Ops/sec |
arrayConcat123 | 1066.5 Ops/sec |
arraySpread123 | 116.9 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Description
The benchmark measures the performance difference between three ways to add an element to the beginning of an array:
unshift()
concat()
with a new array containing the element...
)Options Compared
The benchmark compares the performance of these three approaches, which can be summarized as follows:
unshift()
: Most efficient way to add an element to the beginning of an array, but it requires modifying the original array.concat()
: Creates a new array with the element added at the beginning, resulting in slower performance due to memory allocation. However, it preserves the original array and can be useful when preserving the original data....
): A relatively recent feature introduced in ECMAScript 2015 (ES6), which allows for creating a new array by spreading elements from an existing array. It's faster than concat()
but slower than unshift()
.const
or let
declarations for the variable might not impact performance in this specific benchmark.Library and Syntax
The test cases use native JavaScript features:
...
) is a relatively recent feature introduced in ES6.Benchmark Preparation Code
The script preparation code creates an array with three elements: [1, 2, 3]
. This ensures that each test case starts with the same initial array.
Individual Test Cases
Each test case measures the performance of one specific operation:
arrayUnshift123
: Measures the time taken to add 0
to the beginning of an array using unshift()
.arrayConcat123
: Measures the time taken to create a new array with 0
added at the beginning using concat()
.arraySpread123
: Measures the time taken to create a new array by spreading elements from the original array using the spread operator (...
).Latest Benchmark Result
The benchmark result shows the performance data for each test case, including:
This result provides a snapshot of how these three approaches perform in terms of execution speed on a specific Chrome 128 browser running on Linux.