const arr = Array(1000000).fill(0).map((_, i) => i)
const val = arr.at(-1);
const val = arr[arr.length - 1];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.at() | |
Index |
Test name | Executions per second |
---|---|
Array.at() | 71040160.0 Ops/sec |
Index | 64184620.0 Ops/sec |
The benchmark defined in the provided JSON measures the performance of two different methods for accessing the last element of an array in JavaScript: using the Array.at()
method and traditional array indexing.
Array.at(-1):
arr.at(-1)
retrieves the last element of the array.arr[arr.length - 1]:
Array.at()
.The benchmark results indicate the following:
Array.at(-1)
achieves approximately 71,040,160 executions per second.arr[arr.length - 1]
) achieves approximately 64,184,620 executions per second.Given these results, Array.at()
is faster in this context, which could influence developers when considering performance-critical sections of their code.
Array.at()
could be beneficial for team members unfamiliar with indexing.Aside from the two approaches tested, alternatives for accessing the last element could include:
_.last(array)
), though this may introduce additional overhead.In summary, the benchmark provides a clear comparison between two methods of accessing the last element of an array. The performance metrics indicate that Array.at()
provides a more efficient approach, while also enhancing readability and maintainability. The choice between the two should consider factors, including performance, readability, and browser support.