window.MAX_SIZE = 1000;
const items = [];
for (let i = 0; i < MAX_SIZE; i++) {
items.push(i);
}
let items = [];
for (let i = 0; i < MAX_SIZE; i++) {
items = [items, i];
}
const items = new Array(MAX_SIZE);
for (let i = 0; i < MAX_SIZE; i++) {
items[i] = i;
}
const items = Array.from(new Array(MAX_SIZE), (_, k) => k)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Push item to an array | |
Append an item by spread | |
Direct assign an item to an initialized array | |
Direct assign an item usign Array.from |
Test name | Executions per second |
---|---|
Push item to an array | 194618.2 Ops/sec |
Append an item by spread | 234.9 Ops/sec |
Direct assign an item to an initialized array | 281840.6 Ops/sec |
Direct assign an item usign Array.from | 78561.2 Ops/sec |
Overview of the Benchmark
The provided benchmark, "Add item to array: push vs spread vs assign vs assign with from:", tests four different approaches for adding an item to an array:
push()
...
)Array.prototype.push()
(similar to assign
in some other contexts)Array.from()
constructor.Approaches Compared
The benchmark compares the performance of these four approaches on a large array with 1000 elements, populated with sequential integers from 0 to 999.
push()
: This method appends an item to the end of the array and returns the new length of the array....
): This method creates a new array by copying all elements from the original array and adding the new element.Array.prototype.push()
: This method directly modifies the existing array by pushing the new element to it.Array.from()
constructor: This method creates a new array with the specified length, populated with values generated by the provided callback function.Pros and Cons of Each Approach
push()
:...
)Array.prototype.push()
:push()
.Array.from()
constructor:Library Used
None of the provided benchmark cases use any external libraries.
Special JS Feature/Syntax
The benchmark uses modern JavaScript features, including:
for
loop initialization string ("const items = [];\r\nfor (let i = 0; i < MAX_SIZE; i++) {\r\n items.push(i); \r\n}"
)."items = [...items, i];"
).Other Considerations
When choosing an approach for adding an item to an array, consider the trade-offs between:
In this specific benchmark, the spread operator appears to be the fastest approach, followed closely by direct assignment using Array.from()
. The push()
method is slower due to its overhead of creating a new array element.