function getObj() {
return {x: 0, Y: 0};
}
const array = new Array(1000000).fill(0);
for (let i = 0; i < array.length; i++) array[i] = getObj();
const array = new Array(1000000).fill(0);
for (let i = 0; i < array.length; ++i) array[i] = getObj();
const array = new Array(1000000).fill(0);
const l = array.length;
for (let i = 0; i < l; ++i) array[i] = getObj();
const array = new Array(1000000).fill(0);
for (const i in array) array[i] = getObj();
const array = new Array(1000000).fill(0);
let i;
for (i in array) array[i] = getObj();
const array = new Array(1000000).fill(0);
const arr2 = array.map(_ => getObj());
const arr3 = [];
for (let i = 0; i < 1000000; i++) arr3.push(getObj());
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
1 | |
2 | |
3 | |
4 | |
5 | |
6 | |
7 |
Test name | Executions per second |
---|---|
1 | 16.8 Ops/sec |
2 | 16.9 Ops/sec |
3 | 17.0 Ops/sec |
4 | 6.5 Ops/sec |
5 | 6.5 Ops/sec |
6 | 15.6 Ops/sec |
7 | 15.1 Ops/sec |
Measuring the performance of different ways to allocate and manipulate arrays in JavaScript is a common task.
Benchmark Overview
The benchmark, named "TestArrayAllocationv2", consists of 7 test cases that vary in how they allocate and populate an array with objects. The goal is to determine which approach yields the best performance.
Options Compared
Here are the different approaches compared:
array[i] = getObj();
(test cases: 1, 2, 4, 5)let i; for (i in array) array[i] = getObj();
(test case: 6)for (const i in array) array[i] = getObj();
(test case: 4, 5 is similar but without let i; )array.map(_ => getObj());
(test case: 6)map()
function to create a new array with the same number of elements, where each element is an object created by calling getObj()
.arr3.push(getObj());
(test case: 7)push()
function.Pros and Cons
Here's a brief summary of each approach:
let i
allows the loop variable to "fall through" to the next iteration without declaring it again.Library Considerations
None of these test cases rely on any external libraries that would affect the benchmark results.
Special JS Feature or Syntax
There are a few things worth noting:
_
as the loop variable in array.map(_ => getObj());
is a convention to indicate that the variable name is not important.let i;
syntax in some test cases allows for the loop variable to "fall through" to the next iteration without declaring it again.Other Alternatives
Some alternative approaches that could be included in this benchmark are:
Array.prototype.forEach()
instead of a traditional loopslice()
or other array methods to create a new array and assign elements to it