let myArray = [];
for (let i=0; i<1024; i++) {
myArray.push("foo" + i);
}
let myArray = new Array(1024);
for (let i=0; i<1024; i++) {
myArray.push("foo" + i);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
undefined | |
defined |
Test name | Executions per second |
---|---|
undefined | 24912.1 Ops/sec |
defined | 24021.8 Ops/sec |
Let's break down the test cases and explain what's being tested.
Test Case 1: "undefined"
This test case creates an empty array using let myArray = []
and then uses a for
loop to push 1024 strings onto it. The script preparation code is empty, which means no additional setup or initialization is performed before running the benchmark.
What's being tested: This test case measures the performance of JavaScript arrays when they are initialized with an explicit size using new Array(size)
versus not explicitly initializing them (i.e., letting JavaScript default to a minimum size).
Options compared:
let myArray = []
: This approach creates an array with a dynamic, variable size. The size is determined by the amount of data pushed onto it.let myArray = new Array(1024)
: This approach creates an array with a fixed size of 1024 elements.Pros and Cons:
let myArray = []
)let myArray = new Array(1024)
Library and syntax: This test case doesn't use any external libraries or special JavaScript features. The focus is on measuring the performance difference between two specific array initialization approaches.
Now, let's look at the second test case:
Test Case 2: "defined"
This test case creates an array with a fixed size of 1024 elements using let myArray = new Array(1024)
and then uses a for
loop to push 1024 strings onto it.
The script preparation code is empty, just like the first test case. However, this time we're comparing performance between two different ways of initializing an array with a known size:
Options compared:
let myArray = new Array(1024)
: This approach creates an array with a fixed size of 1024 elements.let myArray = []
(with dynamic growth): This approach creates an array that grows dynamically as data is pushed onto it.Pros and Cons:
let myArray = new Array(1024)
let myArray = []
)Library and syntax: Like the previous test case, this one doesn't use any external libraries or special JavaScript features. The focus is on measuring performance differences between two different initialization approaches.
Other alternatives to these two approaches include:
Array.from()
to create an array from an iterable source.from
function to create an array with a fixed size.std::vector
, which provides guaranteed performance for large datasets.However, since this benchmark is focused on JavaScript, these alternatives are not considered.