var array = [1,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3];
return array[array.length - 1];
return array.at(-1);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array[array.length - 1] | |
array.at(-1) |
Test name | Executions per second |
---|---|
array[array.length - 1] | 8591219.0 Ops/sec |
array.at(-1) | 15673484.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Overview
MeasureThat.net is a platform where users can create and run JavaScript benchmarks to compare different approaches to achieve optimal performance. In this case, we have two test cases: array[array.length - 1]
and array.at(-1)
.
Test Case Description
The first test case uses the array.length
property to access the last element of an array (array[array.length - 1]
). The second test case uses the at()
method with negative indexing to achieve the same result (array.at(-1)
).
Comparison Options
We have two options being compared:
[ ]
notation to access the last element of an array.at()
method with negative indexing to access the last element of an array.Pros and Cons
Here are some pros and cons of each approach:
Direct Indexing (array[array.length - 1]):
Pros:
Cons:
at() Method (array.at(-1))
Pros:
filter()
, map()
)Cons:
at()
method (Chrome 116 and later)Library Usage
The test case uses the built-in Array
object, which is a part of the JavaScript standard library. The at()
method was introduced in ECMAScript 2019 (ES2020) and is now supported by most modern browsers.
Special JS Feature/Syntax
There is no special JS feature or syntax used in these test cases. However, it's worth noting that the use of negative indexing (array.at(-1)
) might require JavaScript engines to optimize for performance.
Other Alternatives
If you want to explore other approaches, here are a few alternatives:
Array.prototype.slice()
with a negative index: array.slice(-1)
(similar to at()
, but without the at()
method)Array.prototype.pop()
or Array.prototype.shift()
: These methods can be used to access the last element of an array, but they may have different performance characteristics and side effects compared to direct indexing or the at()
method._.last(array)
): While not necessary for this specific test case, libraries like Lodash provide additional utility functions that can simplify array operations.Keep in mind that these alternatives might not be as efficient or readable as the original test cases.