var array = [1,2,3];
var d = array[1];
var z = 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] | 165407184.0 Ops/sec |
array.at(-1) | 155829664.0 Ops/sec |
Let's break down the benchmark being tested.
What is being tested?
The provided JSON represents a JavaScript microbenchmark that compares two approaches to access the last element of an array:
array[array.length - 1]
array.at(-1)
These two expressions are being compared to measure their performance difference.
Options compared:
array[array.length - 1]
: This approach uses a property access method to access the last element of the array. It requires calculating the length of the array and then using that value as an index.array.at(-1)
: This approach uses the at()
method, which is a relatively new feature introduced in ECMAScript 2020 (ES2020). The at()
method allows indexing into arrays with a negative offset, making it more readable and concise than the traditional array indexing syntax.Pros and cons of each approach:
array[array.length - 1]
:array.at(-1)
: Library usage:
The benchmark does not explicitly use any external libraries. However, it relies on the at()
method, which is a built-in feature of JavaScript arrays in newer browsers (specifically, Chrome 115 and Safari 537.36).
Special JS features or syntax:
The benchmark uses the new at()
method, which was introduced in ES2020. This syntax allows for more readable and concise indexing into arrays.
Other alternatives:
If you needed to support older browsers or want a different approach, here are some alternative methods:
slice()
method to extract the last element: array.slice(-1)[0]
[Symbol.iterator]
method to iterate over the array and access the last element: for (let i of array) { if (i === 2) { console.log(i); } }
Keep in mind that these alternatives may have different performance characteristics compared to the original approaches being tested.
Why this benchmark is interesting:
This benchmark highlights the importance of considering performance and code readability when writing JavaScript. The use of at()
method demonstrates a new feature that can improve code quality, while still being compatible with older browsers.