Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
Last item in array Slice vs Length - 1 vs .at
(version: 0)
Comparing performance of:
Slice vs Length - 1 vs .at
Created:
2 years ago
by:
Guest
Jump to the latest result
Script Preparation code:
var arr = []; for (let i = 0; i < 1000000; i++) { arr.push(i); }
Tests:
Slice
for (let i = 0; i < 1000; i++) { const v = arr.slice(-1)[0]; }
Length - 1
for (let i = 0; i < 1000; i++) { const v = arr[arr.length - 1]; }
.at
for (let i = 0; i < 1000; i++) { const v = arr.at(-1); }
Rendered benchmark preparation results:
Suite status:
<idle, ready to run>
Run tests (3)
Previous results
Fork
Test case name
Result
Slice
Length - 1
.at
Fastest:
N/A
Slowest:
N/A
Latest run results:
No previous run results
This benchmark does not have any results yet. Be the first one
to run it!
Autogenerated LLM Summary
(model
gemma2:9b
, generated one year ago):
This benchmark tests three different ways to access the last element of an array in JavaScript: * **`slice()`:** This method creates a shallow copy of a portion of the array. In this case, `arr.slice(-1)[0]` extracts the last element from the array using a slice with a length of 1 and then takes the first element of that slice. * **`length - 1`:** This approach directly accesses the last element by using the array's `length` property and subtracting 1 to get the index of the last element. * **`.at()`:** Introduced in ES2019, this method allows you to access an array element by its zero-based index. `arr.at(-1)` retrieves the last element directly using a negative index. **Pros and Cons:** * **`slice()`**: * **Con:** Can be slower due to creating a new copy of the array portion. * **`length - 1`**: * **Pro:** Simple, concise syntax. * **Con:** More susceptible to errors if the array length changes unexpectedly (e.g., if elements are added or removed). * **`.at()`**: * **Pro:** Generally the most performant option as it avoids creating a new array copy and is designed specifically for accessing elements by index. * **Con:** Requires support for ES2019 (or transpilation if targeting older environments). **Other Considerations:** * **Array Size**: The performance difference might be more noticeable with very large arrays. **Alternatives:** While these methods directly access the last element, you could also use a function like `Array.prototype.pop()` to retrieve and remove the last element from the array.
Related benchmarks:
`Array.slice(-1)[0]` vs `Array[Array.length]` for 10000 length
Last item in array Slice vs Length - 1
Test slice vs array.length accessing last element
`array.slice(-1)[0]` vs `array[array.length - 1]`
at(-1) vs slice(-1)[0] vs length - 1
Comments
Confirm delete:
Do you really want to delete benchmark?