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;
}
const items = new Array();
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 | |
Direct assign an item to an empty array |
Test name | Executions per second |
---|---|
Push item to an array | 9688.7 Ops/sec |
Append an item by spread | 1198.9 Ops/sec |
Direct assign an item to an initialized array | 10073.2 Ops/sec |
Direct assign an item to an empty array | 9743.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition and Purpose
The benchmark is designed to compare four different approaches for adding items to an array:
push()
method to add an item to the end of the array....
) to create a new array with the original array and the additional item.items[i] = i;
).The benchmark aims to measure which approach is the fastest for adding items to an array of a fixed size (1000 elements).
Options Compared
Here's a brief summary of each option:
Pros and Cons
Here are some pros and cons for each approach:
Library and Special JS Features
None of the benchmarks use any specific libraries, but they do test some general JavaScript features:
push()
, assign()
, and bracket notation (items[i] = i;
).Other Considerations
When interpreting the results, consider the following:
Alternatives
Other approaches for adding items to an array could include:
concat()
method: Instead of using the spread operator, you could use the concat()
method to create a new array.items[i++] = i;
) instead of the push or assign methods.array.prototype.add()
.Keep in mind that these alternatives may have different trade-offs and implications for performance, readability, and maintainability.