// Array.prototype.concat
function createArray() {
return new Array(1024*8).fill(null).map((value, index) => {
return {
value: index,
index: index,
};
});
}
const params = createArray();
const other = createArray().concat(params);
// spread operator
function createArray() {
return new Array(1024*8).fill(null).map((value, index) => {
return {
value: index,
index: index,
};
});
}
const params = createArray();
const other = [ createArray(), params ];
// push
function createArray() {
return new Array(1024*8).fill(null).map((value, index) => {
return {
value: index,
index: index,
};
});
}
const params = createArray();
const other = createArray().push(params);
// object assign
function createArray() {
return new Array(1024*8).fill(null).map((value, index) => {
return {
value: index,
index: index,
};
});
}
const params = createArray();
const other = Object.assign(createArray(), params);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
spread operator | |
Push | |
Object assign |
Test name | Executions per second |
---|---|
Array.prototype.concat | 5598.9 Ops/sec |
spread operator | 4622.7 Ops/sec |
Push | 4606.3 Ops/sec |
Object assign | 709.4 Ops/sec |
Let's break down what's being tested on the provided JSON.
Benchmark Overview
The benchmark compares four different methods for creating a new array by concatenating or merging an existing large array with another array:
Array.prototype.concat()
...
)push()
methodObject.assign()
methodOptions Compared
createArray()
)push()
and Object.assign()
)Pros and Cons of Each Approach
Array.prototype.concat()
...
)push()
methodObject.assign()
for merging large arrays.Object.assign()
methodLibrary and Syntax
None of these methods rely on specific libraries or syntax features beyond ES6 spread operator (...
).
Other Considerations
When choosing between these methods, consider the following:
Array.prototype.concat()
might be a good choice if performance is not a concern....
) or Object.assign()
method are likely better options due to their efficiency and conciseness.Alternatives
For alternative methods, you can consider:
Array.prototype.push()
with an array of elements to be pushed (e.g., [...arrayToMerge, ...newElements]
).Array.prototype.splice()
or Array.prototype.slice()
to merge arrays.Array.prototype.forEach()
or Array.prototype.reduce()
.Keep in mind that these alternatives might have different performance characteristics and trade-offs compared to the methods being tested here.