var array = [].fill(0, 10, 100)
var array2 = [].fill(0, 20, 100)
array.push(array2)
array = [array, array2]
array = array.concat(array2)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
push | |
spread | |
concat |
Test name | Executions per second |
---|---|
push | 4827876.5 Ops/sec |
spread | 2797246.2 Ops/sec |
concat | 2021051.9 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Overview
The benchmark is designed to compare three different ways to append an array array2
to another array array
. The three methods being compared are:
push()
with spread syntax (...
)[...array, ...array2]
)concat()
methodWhat is tested
The benchmark measures the performance of each method on a large array (10 elements) and its equivalent larger array (20 elements). The test cases are designed to capture the overhead introduced by each method.
Options compared
...
) to create a new array by concatenating array
and array2
. It's a concise way to append elements to an array.[...array, ...array2]
) to create a new array by concatenating array
and array2
. It's a more explicit way to append elements to an array.concat()
method to concatenate array
and array2
. It's a traditional way to merge arrays.Library
None. No external libraries are used in this benchmark.
Special JS feature/syntax
None mentioned in this benchmark. However, note that spread syntax (...
) is a relatively recent addition to JavaScript (introduced in ES6) and may not be supported by older browsers or environments.
Other alternatives
In addition to these three methods, other ways to append elements to an array include:
Array.prototype.push.apply()
Array.prototype.splice()
Array.prototype.unshift()
followed by Array.prototype.slice()
These alternatives may have varying levels of performance and readability compared to the three methods being tested.
Benchmark preparation code
The benchmark preparation code creates two arrays, one with 10 elements and another with 20 elements, using Array.prototype.fill()
:
var array = [].fill(0, 10, 100)
var array2 = [].fill(0, 20, 100)
This code prepares the input data for the benchmark tests.
Individual test cases
Each test case measures the execution time of a specific method:
array.push(...array2)
array = [...array, ...array2]
array = array.concat(array2)
These test cases capture the performance differences between each method.