var array = [1,2,3];
var d = array[array.length - 1];
var z = array.at(-1);
var e = array[array.length + -1]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array[array.length - 1] | |
array.at(-1) | |
array[array.length + -1] |
Test name | Executions per second |
---|---|
array[array.length - 1] | 12378267.0 Ops/sec |
array.at(-1) | 23446644.0 Ops/sec |
array[array.length + -1] | 12257865.0 Ops/sec |
What is being tested?
The provided JSON represents a JavaScript microbenchmarking test case on the MeasureThat.net website. The test focuses on comparing three different ways to access the last element of an array:
array[array.length - 1]
array.at(-1)
array[array.length + -1]
These approaches are used to measure their performance and determine which one is the most efficient.
Options comparison
The three options being compared are:
array[array.length - 1]
: This method uses the -
operator to subtract 1 from the array length, then uses array indexing ([]
) to access the element at that index.array.at(-1)
: This method uses the at()
method introduced in ECMAScript 2019 (ES10), which allows accessing an element at a specific index without bounds checking. The -1
indicates the last element of the array.array[array.length + -1]
: This method is similar to the first option, but with a twist: it adds -1
to the array length instead of subtracting 1.Pros and Cons
Here are some pros and cons of each approach:
array[array.length - 1]
:at()
), easy to understand.array.at(-1)
:at()
method.array[array.length + -1]
:array[at(-1)]
, but with the added benefit of being more readable due to the simpler indexing pattern.Library and purpose
None of the options rely on a specific library. However, note that some JavaScript engines may provide additional features or optimizations for arrays.
Special JS feature or syntax
The at()
method is a new feature introduced in ECMAScript 2019 (ES10). It allows accessing an element at a specific index without bounds checking, making it more efficient and convenient than traditional array indexing methods. The -1
used with at()
refers to the last element of the array.
Other alternatives
If you're interested in exploring alternative ways to access the last element of an array, here are some options:
array[-1]
: This method uses a negative index to access the first element from the end of the array. It's not as efficient as at(-1)
but can be useful in certain scenarios.slice().reverse()[0]
: This method creates a reversed copy of the array using slice()
and then accesses the last element ([0]
). While it works, it's less efficient than the other options due to the creation of an intermediate array.Keep in mind that these alternatives may have different performance characteristics or requirements (e.g., browser support).