var arr = Array(100000000).fill(0);
var a = arr[arr.length - 1];
var b = arr.at(-1);
var c = arr.slice(-1)[0]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
length | |
at | |
slice |
Test name | Executions per second |
---|---|
length | 5251306.5 Ops/sec |
at | 9310570.0 Ops/sec |
slice | 6900354.5 Ops/sec |
This benchmark on MeasureThat.net compares three different ways to access the last element of a very large array in JavaScript. Let's break down each approach:
1. length
: This method uses the length
property of the array to get the index of the last element and then accesses that element directly.
var a = arr[arr.length - 1];
2. at()
: The at()
method allows you to access elements in an array by index, even negative indices. -1
refers to the last element.
var b = arr.at(-1);
length
and provides a more explicit way to access elements by index. 3. slice()
: The slice()
method creates a shallow copy of a portion of an array. Using slice(-1)[0]
, we take a slice starting from the last element and retrieve the first (and only) element in that slice.
var c = arr.slice(-1)[0]
length
or at()
, and can potentially have a minor performance overhead due to creating a new array.Other Considerations:
at()
is generally recommended for its simplicity and performance.Let me know if you'd like to explore any of these aspects further!