var array = [1,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3]
var N = array.length
let sum = 0
for (let i = 0; i < N; i++) sum += array[i]
let sum = 0
for (let i = 0; i < N; i++) sum += array.at(i)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array[i] | |
array.at(i) |
Test name | Executions per second |
---|---|
array[i] | 262712.5 Ops/sec |
array.at(i) | 259925.8 Ops/sec |
I'd be happy to help explain the benchmark.
What is being tested?
MeasureThat.net is comparing two approaches for accessing elements in an array: array[i]
and array.at(i)
. The test case uses an array of 30 elements, where each element appears multiple times.
Options compared:
array[i]
: This approach uses the traditional array indexing syntax, where you specify the index of the element you want to access using square brackets ([]
). For example, array[0]
, array[10]
, etc.array.at(i)
: This approach uses the at()
method, which is a relatively new feature introduced in ECMAScript 2019 (ES2020). The at()
method returns the element at the specified index, and also provides additional features like handling out-of-bounds indices and more.Pros and Cons:
array[i]
:array.at(i)
:Library used:
In this test case, there is no specific library being used. The array data and the benchmarking logic are defined directly in the JavaScript code.
Special JS feature or syntax:
The at()
method is a relatively new feature introduced in ECMAScript 2019 (ES2020). It was added to provide a more modern and expressive way of accessing elements in arrays, while also handling edge cases like out-of-bounds indices.
Other alternatives:
If you were to use alternative approaches for accessing array elements, some options might include:
Array.prototype.indexOf()
or Array.prototype.findIndex()
to find the index of an element, then using indexing (array[index]
) to access it.However, in this specific test case, the comparison is between array[i]
and array.at(i)
, so these alternatives are not relevant.