<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'></script>
var oldArray = [];
for (var i = 1; i<4000; i++) {
oldArray.push({id: i, name: "Name "+ i });
}
var newArray = [{id: 0, name: "All"}].concat(oldArray);
var newArray = oldArray.unshift({id: 0, name: "All"});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
concat | |
unshift |
Test name | Executions per second |
---|---|
concat | 51398.5 Ops/sec |
unshift | 1315.5 Ops/sec |
This benchmark tests the performance of two different methods for adding an element to the beginning of an array in JavaScript: concat()
and unshift()
.
Benchmark Breakdown:
Preparation: The script first creates a large array (oldArray
) containing 3999 objects, each with an 'id' and 'name' property. This simulates a scenario where you have an existing array of data.
Test Cases:
concat()
: This method creates a new array by combining the elements of the original oldArray
with a single element {id: 0, name: "All"}
. unshift()
: This method directly modifies the existing oldArray
by adding the same element ({id: 0, name: "All"}
) to its beginning.Pros and Cons:
concat()
:
unshift()
because it creates a new array object.unshift()
:
Other Considerations:
concat()
can become significantly slower due to the overhead of creating a new array. unshift()
would likely perform better in these scenarios.concat()
. If performance is critical and you're okay modifying the original array, use unshift()
.Alternatives:
The benchmark focuses specifically on adding an element to the beginning of an array. Here are some alternative approaches for working with arrays in JavaScript:
push()
: Adds an element to the end of an array (modifies the original array).splice()
: A versatile method that can insert, remove, or replace elements within an array. It's more complex but offers greater flexibility.map()
, filter()
, and reduce()
, which are often more efficient than manually iterating through arrays.