var params = [ {d:{a:"hello", b:true, c:7},a:"hello", b:true, c:7}, {d:{a:"hello", b:true, c:7},a:"hello", b:true, c:7}, {d:{a:"hello", b:true, c:7},a:"hello", b:true, c:7}, {a:"hello", b:true, c:7} ];
var other = [ {a:"hello", b:true, c:7}, {a:"hello", b:true, c:7}, {a:"hello", b:true, c:7} ].concat(params);
var params = [ {d:{a:"hello", b:true, c:7},a:"hello", b:true, c:7}, {d:{a:"hello", b:true, c:7},a:"hello", b:true, c:7}, {d:{a:"hello", b:true, c:7},a:"hello", b:true, c:7}, {a:"hello", b:true, c:7} ];
var other = [ {a:"hello", b:true, c:7},{a:"hello", b:true, c:7}, params ]
var params = [ {d:{a:"hello", b:true, c:7},a:"hello", b:true, c:7}, {d:{a:"hello", b:true, c:7},a:"hello", b:true, c:7}, {d:{a:"hello", b:true, c:7},a:"hello", b:true, c:7}, {a:"hello", b:true, c:7} ];
var other = [ {a:"hello", b:true, c:7},{a:"hello", b:true, c:7} ].push(params);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
spread operator | |
Push |
Test name | Executions per second |
---|---|
Array.prototype.concat | 11509047.0 Ops/sec |
spread operator | 31233810.0 Ops/sec |
Push | 35008584.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
What is being tested?
The provided benchmark tests three ways to concatenate or add elements to an array in JavaScript:
Array.prototype.concat()
: This method creates a new array by copying all elements from one array and then adding additional arrays or elements....
): Introduced in ECMAScript 2015 (ES6), this syntax allows you to expand an array into a list of arguments, creating a new array.Array.prototype.push()
: This method adds one or more elements to the end of an existing array.Options comparison
Here's a brief overview of each option and their pros and cons:
Array.prototype.concat()
:...
):Array.prototype.push()
:Library usage
None of the tested options rely on external libraries.
Special JavaScript features/syntax
The spread operator (...
) is a relatively new feature introduced in ECMAScript 2015 (ES6). It allows you to expand an array or object into a list of arguments, creating a new array. This syntax was adopted by modern browsers and JavaScript engines.
Other alternatives
While not explicitly tested in the provided benchmark, other alternatives for concatenating or adding elements to arrays include:
Array.prototype.slice()
followed by Array.prototype.concat()
concat
functionKeep in mind that these alternatives might not be as efficient or concise as the tested options.
Benchmark result interpretation
The benchmark results show the execution times for each test case on a Chrome 107 browser running on a Mac OS X 10.15.7 system. The order of execution times is:
Array.prototype.push()
: ~35 seconds per second...
): ~31 seconds per secondArray.prototype.concat()
: ~12 seconds per secondThis suggests that, in this specific test case and configuration, the spread operator is the fastest option, followed closely by Array.prototype.push()
.