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;
}
--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 |
Test name | Executions per second |
---|---|
Push item to an array | 167241.3 Ops/sec |
Append an item by spread | 1002.6 Ops/sec |
Direct assign an item to an initialized array | 415122.9 Ops/sec |
Let's break down what is being tested in the provided JSON.
Benchmark Definition
The benchmark tests three different approaches to add an item to an array:
push()
method to add an item to the end of an array....
) to create a new array with the original array and the new item.Options Compared
The benchmark compares the performance of these three approaches:
Library Usage
None of the benchmark cases use any external libraries.
Special JS Features/Syntax
The benchmark does not mention any special JavaScript features or syntax. The code only uses standard JavaScript syntax and built-in methods.
Alternative Approaches
Other approaches to add an item to an array include:
concat()
: Instead of push, you can use the concat()
method to create a new array with the original array and the new item.Array.prototype.push.apply()
: This method applies the push()
method to the array, which can be more efficient for large arrays.It's worth noting that these alternative approaches may have different performance characteristics compared to push, spread, or direct assign.