const arr = [];
for(let i = 0; i < 100; i++) {
arr[arr.length] = i;
}
const arr = [];
for(let i = 0; i < 100; i++) {
arr.push(i);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
direct assignment | |
push |
Test name | Executions per second |
---|---|
direct assignment | 2667428.2 Ops/sec |
push | 1839423.5 Ops/sec |
Benchmark Explanation
The provided benchmark measures the performance difference between two approaches for initializing an array in JavaScript: direct assignment using the []
syntax and pushing elements to the array using the push()
method.
Approach Comparison
There are two main approaches compared:
[]
) to initialize an empty array. The for
loop then appends elements to this array.push()
method to add elements to an existing array, which is initially created with the const arr = []
syntax.Pros and Cons of Each Approach
push()
method, especially for larger arrays.Library and Special JS Features
Neither of the benchmark tests uses a specific library or special JavaScript feature. The focus is on comparing the performance of two basic approach to array initialization in JavaScript.
Other Alternatives
If you were to write your own benchmark for this scenario, you could also consider using:
...
): Can be used to create a new array from an existing one or push elements onto it.For example:
const arr = [];
for (let i = 0; i < 100; i++) {
arr.set(i, i);
}
or
const arr = [1, 2, 3];
arr.push(...Array(97).fill().map((_, i) => i + 4));
Keep in mind that the performance differences between these approaches may be small and dependent on specific use cases.