<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'></script>
var arr1 = [];
var arr2 = [];
for (let i = 0; i < 200000; i += 1) {
arr1.push(i);
}
for (let i = 0; i < 5000; i += 1) {
arr2.push(-1 * i);
}
var other = arr1.concat(arr2);
var other = [arr1, arr2]
var other = [];
other.push(arr1);
other.push(arr2);
var other = [];
for (let i = 0; i < arr1.length; i += 1) {
other.push(arr1[i]);
}
for (let i = 0; i < arr2.length; i += 1) {
other.push(arr2[i]);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
spread operator | |
Push | |
loop with singular push |
Test name | Executions per second |
---|---|
Array.prototype.concat | 1347.6 Ops/sec |
spread operator | 572.4 Ops/sec |
Push | 0.0 Ops/sec |
loop with singular push | 59.0 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Overview
The benchmark is designed to compare three different approaches for concatenating arrays in JavaScript:
Array.prototype.concat()
...
)Options Compared
The test cases are comparing the performance of these three approaches:
Array.prototype.concat()
: This method creates a new array and copies all elements from the original arrays into it....
): This operator creates a new array by spreading elements from one or more source arrays.Pros and Cons of Each Approach
Array.prototype.concat()
:...
):concat()
due to overhead of spreading elements.Library Used
The benchmark uses jQuery as a dependency for testing. This is likely used to provide a consistent DOM environment across different browsers.
Special JS Feature/Syntax
None mentioned explicitly in the provided information.
Other Alternatives
If you need further optimization or have specific use cases, consider these alternatives:
Array.prototype.reduce()
: Instead of concatenating arrays, use reduce()
to create a new array with accumulated elements.Array.prototype.push.apply()
: For pushing multiple elements onto an array using a single function call.Additional Considerations
When choosing an approach for concatenating arrays in JavaScript:
Remember, this benchmark is designed to provide a general idea of performance differences between these approaches. Depending on your specific requirements, you may need to experiment further to find the optimal solution for your application.