Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
at VS slice VS length: who is the fastest to get last item
(version: 0)
Comparing performance of:
at vs slice vs length
Created:
3 years ago
by:
Guest
Jump to the latest result
Script Preparation code:
var list = []; for (var i = 0; i < 1000; i++) { list.push(i); }
Tests:
at
last = list.at(-1);
slice
last = list.slice(-1)[0];
length
last = list[list.length -1]
Rendered benchmark preparation results:
Suite status:
<idle, ready to run>
Run tests (3)
Previous results
Fork
Test case name
Result
at
slice
length
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: * **`at(-1)`:** This method uses the `at()` function introduced in ES2022. It's designed specifically for accessing elements by index, even negative ones. * **`slice(-1)[0]`:** This approach utilizes the `slice()` method to extract a subarray starting from the last element (-1) and then taking the first element ([0]) of that subarray. * **`list[list.length -1]`:** This is the traditional method, accessing the array element directly using its index, calculated as the length of the array minus 1. **Pros and Cons:** * **`at(-1)`:** Cleanest syntax, potentially most performant due to being optimized specifically for this task in modern engines. * **`slice(-1)[0]`:** Widely understood, works consistently across JavaScript versions. Might be slightly less efficient than `at()` as it involves creating a new subarray. * **`list[list.length - 1]`:** Well-established, familiar to most developers. Can be less readable than the other options. **Considerations:** * **Performance:** The benchmark results show that `at(-1)` is generally the fastest. However, performance can vary depending on factors like JavaScript engine and array size. * **Readability:** `at(-1)` offers the most concise syntax, making the code easier to read. `slice(-1)[0]` is also readable but slightly more verbose. **Alternatives:** While not directly compared in this benchmark, there are other ways to access the last element of an array: * **Using `Array.prototype.pop()`:** This method removes and returns the last element of an array. * **Storing the last element separately:** Maintain a variable that tracks the last element as you iterate through the array. Let me know if you have any more questions!
Related benchmarks:
slice VS splice: who is the fastest to keep constant size
array.prototype.at() vs array[array.length - 1]
Test slice vs array.length accessing last element
`array.slice(-1)[0]` vs `array[array.length - 1]`
Comments
Confirm delete:
Do you really want to delete benchmark?