var n = 10000000
const arr = [];
for (let i = 0; i < n; i++) {
arr.push(i);
}
const arr = new Array(n);
for (let i = 0; i < n; i++) {
arr[i] = i;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Dynamic | |
Pre Allocated |
Test name | Executions per second |
---|---|
Dynamic | 4.2 Ops/sec |
Pre Allocated | 4.2 Ops/sec |
Let's break down the benchmark and explain what is being tested.
Benchmark Overview
The benchmark, titled "JS Build Big Array", measures the performance of JavaScript arrays in different ways. The script preparation code sets the n
variable to 10 million, which will be used as the size of the array being built.
Script Preparation Code Options
There are two options for preparing the script:
const arr = [];
for (let i = 0; i < n; i++) {
arr.push(i);
}
n
elements before populating it.const arr = new Array(n);
for (let i = 0; i < n; i++) {
arr[i] = i;
}
Comparison
The comparison between these two approaches is mainly in terms of memory allocation and the overhead of creating an array with a fixed size versus dynamically allocating it.
Pros and Cons
Other Considerations
Array.prototype.push()
and new Array()
. No external libraries are used in this example.Special JS Features or Syntax
This benchmark does not use any special JavaScript features or syntax that would affect its outcome.
Alternative Benchmarks
Other benchmarks could explore similar scenarios, such as:
splice()
versus push()
.for
, forEach
, map()
) for populating an array.These alternative benchmarks can help provide a more comprehensive understanding of JavaScript array performance and the impact of various optimization techniques on real-world applications.