const arr = new Array(512).fill(0).map(() => Math.round(Math.random() * 512));
const at = (arr, idx) => arr[(idx < 0 ? arr.length + idx : idx)];
for (let i = 0; i < arr.length; i++) arr[i] += 1; // access all elements first to allow browser engine optimization if any.
fn1();
fn2();
fn3();
function fn1() {
arr.at(5);
arr.at(2);
arr.at(50);
arr.at(20);
arr.at(500);
arr.at(200);
arr.at(-1);
}
function fn2() {
at(arr, 5);
at(arr, 2);
at(arr, 50);
at(arr, 20);
at(arr, 500);
at(arr, 200);
at(arr, -1);
}
function fn3() {
arr[5];
arr[2];
arr[50];
arr[20];
arr[500];
arr[200];
arr[arr.length - 1];
}
fn1();fn1();fn1();fn1();fn1();fn1();fn1();fn1();fn1();fn1();fn1();
fn2();fn2();fn2();fn2();fn2();fn2();fn2();fn2();fn2();fn2();fn2();
fn3();fn3();fn3();fn3();fn3();fn3();fn3();fn3();fn3();fn3();fn3();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
arr.at(idx) | |
at(arr, idx) | |
arr[idx] |
Test name | Executions per second |
---|---|
arr.at(idx) | 641519.1 Ops/sec |
at(arr, idx) | 26017568.0 Ops/sec |
arr[idx] | 26553486.0 Ops/sec |
The benchmark you're examining compares three different methods for accessing array elements in JavaScript, specifically:
Array.prototype.at()
method.at()
.arr[idx]
.arr.at(idx)
:
arr.at(-1)
easily retrieves the last element.Custom at(arr, idx)
Function:
Array.prototype.at()
, specifically designed to handle both positive and negative indices.arr.at()
.at()
method isn't available.Traditional Array Indexing arr[idx]
:
arr[arr.length - 1]
to access the last element.The benchmark is conducted in a controlled manner, where it first initializes an array of 512 random integers and then performs the access operations in sequence to mitigate any optimization issues related to how browsers handle arrays.
The results show that direct indexing arr[idx]
has the highest executions per second iteration rate, indicating it is the fastest method under typical conditions. The polyfill at(arr, idx)
is nearly as fast, while the native arr.at(idx)
demonstrates the slowest performance in this specific benchmark. This may vary across different browsers or updates as JavaScript engines evolve.
Apart from these three methods, developers can consider the following alternatives:
Understanding these options and their trade-offs can help developers make informed decisions about which method to use in their code, balancing performance, readability, and compatibility with the target environment.