const array = [1,2,3,4,5,6,7,8,9,10,11,12,13];
const array = [1,2,3,4,5,6,7,8,9,10,11,12,13];
array.at(-1);
const array = [1,2,3,4,5,6,7,8,9,10,11,12,13];
array.slice(-1);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array.at(-1); | |
array.slice(-1); |
Test name | Executions per second |
---|---|
array.at(-1); | 221482864.0 Ops/sec |
array.slice(-1); | 65879152.0 Ops/sec |
Let's break down the provided benchmark.
Benchmark Definition
The benchmark is comparing two approaches to access the last element of an array in JavaScript: Array.at(-1)
and Array.slice(-1)
. The purpose of this benchmark is to determine which approach is faster on a specific test case, as specified in the "Script Preparation Code".
Options Compared
There are only two options being compared:
Array.at(-1)
: This method uses the at()
method to access an element at a specified index. In this case, the negative of the index -1
is used to get the last element.Array.slice(-1)
: This method returns a new array containing the last element of the original array.Pros and Cons
Array.at(-1)
slice()
.Array.slice(-1)
slice()
to get a subset).Library and Purpose
None are explicitly mentioned in this benchmark.
Special JS Features or Syntax
The benchmark uses modern JavaScript features such as:
const
(block scope declaration)\r\n
)=>
) (although not used here, it's implied)These features are part of the ECMAScript standard and are widely supported in modern browsers.
Other Alternatives
If you want to compare performance with other methods to access the last element of an array:
array[array.length - 1]
: This uses direct indexing on the array, which is equivalent to Array.slice(-1)
. However, it's generally considered less readable and might not be as efficient in some cases.Object.keys(array)[-1]
: This uses Object.keys()
to get an array of keys for the object (which is an array), and then takes the last key using indexing. While this works, it's a more complex and slower approach.For this specific benchmark, only two approaches (Array.at(-1)
and Array.slice(-1)
) are being compared.