var array = [];
for (let i = 0; i < 1000; ++i) {
array[i] = i;
}
var results = [];
results.push(array[array.length - 1]);
results.push(array.at(-1));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array[array.length - 1] | |
array.at(-1) |
Test name | Executions per second |
---|---|
array[array.length - 1] | 10235121.0 Ops/sec |
array.at(-1) | 14406814.0 Ops/sec |
Let's break down the provided benchmark definition and test cases.
What is being tested?
MeasureThat.net is testing two different ways to access the last element of an array in JavaScript: array[array.length - 1]
(also known as indexing) and array.at(-1)
(introduced in ECMAScript 2019). The goal is to compare their performance.
Options being compared
The benchmark compares two approaches:
array[array.length - 1]
): This method involves accessing the last element of an array by its index, which is calculated as length - 1
. This approach has been used for a long time in JavaScript.array.at(-1)
): This method was introduced in ECMAScript 2019 and provides a more concise way to access the last element of an array. It uses the at()
function, which takes two arguments: an index (in this case, -1
) and a options object.Pros and cons
Here are some pros and cons for each approach:
Indexing (array[array.length - 1]
)
Pros:
Cons:
at()
method due to additional overhead (e.g., checking if the array has at least one element)array[length - 1]
instead of just array.at(-1)
)Array.prototype.at() (array.at(-1)
)
Pros:
Cons:
Other considerations
The benchmark also uses a common approach for measuring performance: creating an array of 1000 elements, filling it with numbers from 0 to 999, and then pushing the results of both indexing methods onto an array.
Library usage (none)
There are no libraries used in this benchmark.
Special JS features or syntax
The at()
method is a new JavaScript feature introduced in ECMAScript 2019. It provides a more concise way to access elements in arrays, but its availability can vary across browsers and versions.
In summary, the benchmark compares the performance of two approaches for accessing the last element of an array: indexing (array[array.length - 1]
) and the new at()
method (array.at(-1)
). The pros and cons of each approach are discussed, along with some considerations for implementing this benchmark.