var array = [1,2,3,4,5,6,7,8,9];
var array2 = [1,1,1];
array.unshift(array2);
array = array.concat(array2)
array = [array2 , array]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
arrayUnshift123 | |
arrayConcat123 | |
arraySpread123 |
Test name | Executions per second |
---|---|
arrayUnshift123 | 19592.8 Ops/sec |
arrayConcat123 | 376.4 Ops/sec |
arraySpread123 | 89.7 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
What is being tested?
The provided JSON represents a benchmark test case that compares three different approaches to add elements to an array in JavaScript:
array.unshift(...array2);
array = array.concat(array2)
[...array, ...array2]
(using the spread operator)Options being compared:
Each option has its own pros and cons:
array.unshift(...array2);
: This approach adds elements to the beginning of the array. The main advantage is that it can be more efficient when inserting multiple elements at once, as unshift
only creates a new array with the elements in the correct order, without shifting all existing elements. However, this approach can lead to memory allocation overhead for large arrays.array = array.concat(array2)
: This approach concatenates two arrays and assigns the result back to the original array. The main disadvantage is that it creates a new array object each time, which can be inefficient for large datasets. Additionally, concat
may not preserve the original array's properties or methods.[...array, ...array2]
(using the spread operator): This approach uses the spread operator to create a new array by copying elements from the original array and adding the elements from the second array. The main advantage is that it creates a shallow copy of the arrays, which can be more efficient in terms of memory allocation. However, this approach may not preserve the original array's properties or methods.Library usage:
None of the provided options rely on any external libraries.
Special JS features/syntax:
The spread operator ([...array, ...array2]
) is used to create a new array by spreading elements from an existing array. This feature was introduced in ECMAScript 2015 (ES6) as part of the syntax.
Other alternatives:
Some alternative approaches for adding elements to an array include:
push
or splice
: These methods add elements to the end or at a specific position in the array, respectively.Array.prototype.set
: This method sets all elements in an array to new values (not applicable in this case).Array.prototype.slice
and concat
: While not exactly the same as using push
or splice
, these methods can achieve similar results.It's worth noting that the choice of approach depends on the specific use case, such as performance requirements, memory constraints, or desired behavior.