var data = Array(1000000).fill({ filtering: true, mapping: 42 });
data[data.length - 1]
data.at(-1)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Test length | |
Test at |
Test name | Executions per second |
---|---|
Test length | 15985812.0 Ops/sec |
Test at | 28831622.0 Ops/sec |
Let's break down what's being tested in the provided JSON benchmark.
Benchmark Definition
The primary test case measures the access speed of two different ways to access the last element of an array:
arr.at(-1)
arr[arr.length-1]
These two approaches are used to compare their performance, with the goal of determining which one is faster and more efficient.
Options Compared
We have two main options being compared:
at()
method: Introduced in ECMAScript 2019 (ES9), this method provides a safer way to access array elements by their index, without throwing an error if the index is out of bounds.[]
) with length
property: This is the traditional way of accessing array elements using their index.Pros and Cons
at()
MethodPros:
Cons:
[]
) with length
PropertyPros:
at()
method for small arrays.Cons:
at()
method for large arrays.Library
There are no libraries mentioned in this benchmark. The tests only rely on built-in JavaScript features.
Special JS Feature or Syntax
The at()
method is a special feature introduced in ECMAScript 2019 (ES9), which allows safe array indexing without throwing an error if the index is out of bounds. This syntax was not available in earlier versions of JavaScript.
Other Considerations
When evaluating these two approaches, it's essential to consider the size and complexity of the arrays being accessed, as well as the specific requirements of your application. For small arrays or simple use cases, the subscript notation might be sufficient and faster. However, for large arrays or performance-critical code paths, the at()
method can provide a safer and potentially more efficient alternative.
Alternatives
Other alternatives to access the last element of an array include:
pop()
method: This removes the last element from the array and returns it.[...]
): This creates a new array containing only the last element.These alternatives may have different performance characteristics and use cases compared to the at()
method and subscript notation.