var a = Array(100_000_000).fill(1);
let total = 0;
for (let i = 0; i < a.length; i++) {
total += a[i];
}
let total = 0;
for (let i = 0; i < a.length; i++) {
total += a.at(i);
}
let total = 0;
for (let i = 0; i < a.length; i++) {
total += a?.[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
[i] | |
.at(i) | |
?.[i] |
Test name | Executions per second |
---|---|
[i] | 6.0 Ops/sec |
.at(i) | 4.2 Ops/sec |
?.[i] | 4.5 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and considered.
Benchmark Definition
The benchmark is defined by a JSON object that provides information about two approaches:
[i]
(square bracket notation).at(i)
(dot notation)Both approaches are used to access elements in an array a
with a length of 100 million elements, filled with the value 1.
Script Preparation Code
The script preparation code creates the array a
and fills it with 100 million elements.
var a = Array(100_000_000).fill(1);
This code is executed before running each test case.
Html Preparation Code
There is no HTML preparation code provided, which means that the benchmark only focuses on JavaScript performance.
Test Cases
There are three individual test cases:
[i]
: This test case uses the square bracket notation to access elements in the array a
..at(i)
: This test case uses the dot notation to access elements in the array a
.?.[i]
: This test case uses optional chaining (.?
) followed by square bracket notation to access elements in the array a
.Optional Chaining
The test case ?.[i]
uses optional chaining, which is a feature introduced in ECMAScript 2020. Optional chaining allows you to access nested properties or arrays without throwing an error if they are undefined.
total += a?.[i];
If a[i]
is undefined, the expression will evaluate to undefined
instead of throwing an error.
Library and Features
There is no library used in this benchmark. However, the use of optional chaining (?.
) might be considered a feature of modern JavaScript.
Performance Considerations
The performance differences between these three approaches are likely due to the following factors:
[i]
case, we need to increment an index variable i
for each iteration, which might introduce some overhead due to incrementation and array bounds checking.Object.hasOwn(a, 'i')
instead of a.hasOwnProperty('i')
).Benchmark Results
The latest benchmark results show that:
[i]
: 5.982 executions per second?.[i]
: 4.470 executions per second.at(i)
: 4.199 executions per secondBased on these results, the order of performance is: [i]
> ?.[i]
> .at(i)
.
Alternatives
Other alternatives to test this benchmark could include:
Keep in mind that these alternatives might change the focus of the benchmark and may not provide comparable results.
I hope this explanation helps! Let me know if you have any further questions.