var arr1 = [];
var arr2 = [];
for(let i=0; i<10; ++i){
arr1.push("phantasy")
arr1.push("joesguns")
arr1.push("max-hardware")
arr1.push("sigma-cosmetics")
arr1.push("harakiri-sushi")
arr1.push("foodnstuff")
arr1.push("hong-fang-tea")
arr1.push("iron-gym")
arr2.push("nectar-net")
arr2.push("omega-net")
arr2.push("silver-helix")
arr2.push("zer0")
arr2.push("n00dles")
arr2.push("neo-net")
arr2.push("the-hub")
arr2.push("crush-fitness")
}
var other = arr1.concat(arr2);
var arr1 = [];
var arr2 = [];
for(let i=0; i<10; ++i){
arr1.push("phantasy")
arr1.push("joesguns")
arr1.push("max-hardware")
arr1.push("sigma-cosmetics")
arr1.push("harakiri-sushi")
arr1.push("foodnstuff")
arr1.push("hong-fang-tea")
arr1.push("iron-gym")
arr2.push("nectar-net")
arr2.push("omega-net")
arr2.push("silver-helix")
arr2.push("zer0")
arr2.push("n00dles")
arr2.push("neo-net")
arr2.push("the-hub")
arr2.push("crush-fitness")
}
var other = arr1.push(arr2);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
Push |
Test name | Executions per second |
---|---|
Array.prototype.concat | 1501445.8 Ops/sec |
Push | 1197508.1 Ops/sec |
I'll dive into explaining the benchmark.
What is being tested?
The provided JSON represents a JavaScript microbenchmark that compares two approaches for adding elements to an array: the traditional concat()
method and the new ES6 spread operator (...
).
Options compared
There are two test cases:
concat()
method, which concatenates two or more arrays and returns a new array.push()
method, which adds one or more elements to the end of an array.Pros and cons of each approach
push()
for large arrays, and may incur additional memory allocations.concat()
.concat()
when adding multiple elements.Library
None of these approaches rely on a specific library. They are built-in JavaScript methods.
Special JS feature/syntax
The spread operator (...
) is a new feature introduced in ES6 (ECMAScript 2015). It allows for more concise syntax for adding elements to arrays and objects.
Other considerations
push()
with the spread operator may be faster due to reduced memory allocations.concat()
provides more control over the resulting array structure.concat()
and the spread operator ultimately depends on personal preference, coding style, and specific use cases.Alternatives
Other approaches for adding elements to an array include:
arr.push()
: This approach is similar to the original implementation but uses a more traditional loop structure.Array.prototype.set()
: This approach adds all elements from another array to the end of the current array, but it's not supported in older browsers.Keep in mind that these alternatives might have different performance characteristics, syntax complexities, and compatibility issues depending on the specific use case.