const n = 10000
var arr = new Array(n).fill(0);
for (let i = 0; i < n; i++) {
arr[i] = i;
}
for (let i = 0; i < arr.length; i++) {
arr[i] = i * 2;
}
const copy = [];
for (let i = 0; i < arr.length; i++) {
const item = arr.shift();
copy.push(item * 2);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Mutate | |
Copy & Shift |
Test name | Executions per second |
---|---|
Mutate | 861.2 Ops/sec |
Copy & Shift | 14772017.0 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, the different approaches compared, their pros and cons, and other considerations.
Benchmark Definition
The benchmark is designed to test how efficiently JavaScript arrays can be mutated. The script preparation code initializes an array of 10,000 zeros and fills it with incremental values from 0 to 9,999 using a for loop.
Script Preparation Code
const n = 10000;
var arr = new Array(n).fill(0);
for (let i = 0; i < n; i++) {
arr[i] = i;
}
This code creates an array of length n
and fills it with incremental values.
Individual Test Cases
There are two test cases:
for (let i = 0; i < arr.length; i++) {
arr[i] = i * 2;
}
Pros: Simple and straightforward.
Cons: May not be efficient due to unnecessary copies of the array elements.
Array.prototype.shift()
and pushes the doubled value onto the new array.const copy = [];
for (let i = 0; i < arr.length; i++) {
const item = arr.shift();
copy.push(item * 2);
}
Pros: May be more efficient due to avoiding unnecessary copies of the original array elements.
Cons: Requires two array operations, which may introduce additional overhead.
Library Usage
There is no explicit library usage in this benchmark. However, Array.prototype.fill()
and Array.prototype.shift()
are built-in JavaScript methods that are likely implemented by the browser or engine used for testing.
Special JS Features/Syntax
There are no special JavaScript features or syntax used in this benchmark that would require additional explanation.
Other Alternatives
Some alternative approaches to mutating an array could include:
Array.prototype.map()
and assigning the result back to the original array.Array.from()
and pushing the doubled values onto it.These alternatives may have different trade-offs in terms of performance, readability, and complexity. The benchmark is likely designed to favor the "Copy & Shift" approach due to its simplicity and potential efficiency gains.