var array = [0, 1, 2, 3];
let lastWithAtArray = array.at(-1)
let lastWithLength = array[array.length - 1]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array.prototype.at() | |
array[array.length - 1] |
Test name | Executions per second |
---|---|
array.prototype.at() | 159928672.0 Ops/sec |
array[array.length - 1] | 176036736.0 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition
The benchmark is comparing two approaches to reach the last item of an array:
array.prototype.at()
array[array.length - 1]
What is being tested?
The benchmark is testing which approach is faster when trying to access the last element of an array using these methods.
Options compared
There are two options being compared:
array.prototype.at(-1)
(the "at" method)array[array.length - 1]
Pros and Cons
Option A (array.prototype.at()
) Pros:
Cons:
at
method (not all browsers or versions)Option A (array.prototype.at()
) Cons:
Option B (array[array.length - 1]
) Pros:
Cons:
Library used
There is no explicit library mentioned in the benchmark definition. However, array.prototype.at()
is a built-in method introduced in ECMAScript 2019.
Special JS feature/syntax
The "at" method uses a special syntax called "rest operator" (...
) which was introduced in ECMAScript 2015. This allows for more concise and expressive array iteration.
Other considerations
Alternatives
Other alternatives to access the last element of an array could include:
array[0]
followed by a loop that increments the indextail()
function, which provides a more concise and expressive way to access the tail of an array.for (let i = 0; i < array.length - 1; i++)
It's worth noting that the "at" method is generally considered a better option for accessing array elements in modern JavaScript development due to its conciseness and expressiveness. However, older browsers or versions may not support this method, making direct indexing a safer choice in those cases.