var arr = [];
for (let i = 0; i < 1000000; i++) {
arr.push(i);
}
for (let i = 0; i < 1000; i++) {
const v = arr.slice(-1)[0];
}
for (let i = 0; i < 1000; i++) {
const v = arr[arr.length - 1];
}
for (let i = 0; i < 1000; i++) {
const v = arr.at(-1);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Slice | |
Length - 1 | |
Array.at |
Test name | Executions per second |
---|---|
Slice | 25923.3 Ops/sec |
Length - 1 | 1788746.8 Ops/sec |
Array.at | 894956.0 Ops/sec |
What is being tested?
The provided JSON represents a JavaScript microbenchmark test case. It's testing three different approaches to access the last item in an array:
arr.slice(-1)[0]
: This approach uses the slice
method to get the last element of the array and then extracts its value using indexing ([0]
).arr[arr.length - 1]
: This approach directly accesses the last element of the array by subtracting 1 from the length of the array.arr.at(-1)
: This approach uses the new at
method (introduced in JavaScript ES6) to access the last element of the array.Options comparison
Here's a brief overview of each approach:
slice
and indexing is a safe way to access array elements, as it returns a new array with the desired elements. However, this approach may incur additional overhead due to the creation of a new array.slice
method or any potential errors in indexing.at
method provides a convenient and expressive way to access specific elements in an array. However, it's only available in modern browsers that support ES6+ features.Library usage
None of the provided benchmark tests use external libraries or frameworks. The code is self-contained and relies on built-in JavaScript functionality.
Special JS features or syntax
The at
method is a special feature introduced in JavaScript ES6, which allows accessing array elements by their index using dot notation (arr.at(0)
). This approach is only supported in modern browsers that implement ES6+ features.