var array = Array({ length: 10000 }, (_, i) => i);
array.at(-1);
array[array.length - 1]
array.slice(-1)[0]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
at(-1) | |
length - 1 | |
slice(-1)[0] |
Test name | Executions per second |
---|---|
at(-1) | 170825744.0 Ops/sec |
length - 1 | 155702160.0 Ops/sec |
slice(-1)[0] | 58208616.0 Ops/sec |
Let's break down what's being tested in the provided JSON.
Benchmark Definition
The benchmark is testing three different ways to access the last element of an array:
array.at(-1)
array[array.length - 1]
array.slice(-1)[0]
These methods are being compared to determine which one is the fastest and most efficient.
Options Compared
The three options being compared are:
at(-1)
: This method uses the Array.prototype.at()
method, which was introduced in ECMAScript 2022. It allows accessing an element at a specific index using a dot notation.slice(-1)[0]
: This method uses the Array.prototype.slice()
method to create a new array containing only the last element of the original array. The -1
index is then used to access that element.length - 1
: This method directly calculates the index of the last element by subtracting 1 from the length of the array.Pros and Cons
Here's a brief overview of each approach:
at(-1)
: Pros:slice(-1)[0]
: Pros:length - 1
: Pros:Library and Purpose
There is no specific library mentioned in the provided JSON. However, Array.prototype.at()
is a new method introduced in ECMAScript 2022, which allows accessing an element at a specific index using a dot notation.
Special JS Feature
The at(-1)
method uses the Array.prototype.at()
method, which is a special feature introduced in ECMAScript 2022. This feature allows accessing an element at a specific index using a dot notation, making the code more concise and expressive.
In summary, the benchmark is testing three different ways to access the last element of an array: at(-1)
, slice(-1)[0]
, and length - 1
. The at(-1)
method uses a new feature introduced in ECMAScript 2022, while slice(-1)[0]
uses a widely supported approach but may create a new array. The length - 1
method is a simple and efficient way to calculate the index but requires manual calculation.
Alternatives
Other alternatives for accessing the last element of an array include:
Math.max()
with -Infinity
as the first argument: Math.max(-Infinity, array[array.length - 1])
Array.prototype.indexOf()
with -1
as the target value: array[array.length - 1] === array.indexOf(array[array.length - 1]) ? array[array.length - 1] : undefined
These alternatives may offer different trade-offs in terms of performance, memory usage, and readability.