var array = [];
for (let i = 0; i < 1000; ++i) {
array[i] = i;
}
var results = [array[array.length - 1]];
var results = [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] | 9057766.0 Ops/sec |
array.at(-1) | 16212215.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition: The benchmark is designed to compare two approaches for accessing the last element of an array in JavaScript:
array[array.length - 1]
array.at(-1)
The goal is to determine which approach is more efficient and less prone to Out Of Memory (OOM) errors.
Options Compared:
array[array.length - 1]
: This method uses array indexing, which creates a new reference to the last element in the array. The length of the array is calculated at runtime, which can lead to OOM errors if the array grows too large.array.at(-1)
: This method was introduced in ECMAScript 2019 (ES11) as part of the Array.prototype.at() method. It allows direct access to the last element of an array without creating a new reference, making it more memory-efficient.Pros and Cons:
array[array.length - 1]
:array.at(-1)
:Other Considerations:
array.at(-1)
method is specifically designed to handle arrays with many elements without creating new references, making it a more suitable choice for large datasets.Library Usage: There are no libraries mentioned in the provided code snippet. However, it's essential to note that some JavaScript engines or browsers might have built-in optimizations or special handling for certain library functions or methods.
Special JS Features/Syntax:
The at()
method is a modern feature introduced in ECMAScript 2019 (ES11). It allows direct access to the last element of an array without creating a new reference. If you're targeting older browsers, this feature might not be supported.
Other Alternatives:
If array.at(-1)
is not supported by your target browser, you can consider using other alternatives:
array[array.length - 1]
: This method creates a new reference to the last element, similar to array[array.length - 1]
.Array.prototype.slice().at(-1)
: This method creates a new array with the last element and then accesses it using at()
.