var arr = Array.from(Array(100).keys());
arr.slice(-1)[0];
arr[arr.length - 1];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
`Array.slice` | |
`Array.length-1` |
Test name | Executions per second |
---|---|
`Array.slice` | 27681456.0 Ops/sec |
`Array.length-1` | 21536700.0 Ops/sec |
The provided JSON represents two microbenchmarks for measuring the performance of JavaScript arrays. The benchmarks compare two approaches to access the last element of an array: using arr.slice(-1)
and arr[arr.length - 1]
.
Approaches Compared
There are two main approaches being compared:
arr.slice(-1)
: This method creates a new array containing only the last element of the original array. The -1
index refers to the last element in the array.arr[arr.length - 1]
: This method directly accesses the last element of the array without creating a new array.Pros and Cons
arr.slice(-1)
arr[arr.length - 1]
slice(-1)
.Library and Special JS Feature
Neither of these approaches uses any specific JavaScript library. However, they do utilize a common JavaScript feature: array indexing. Both methods rely on the property access syntax arr[index]
to access elements in an array.
Other Considerations
slice(-1)
can provide more predictable behavior and safety guarantees, especially when working with large arrays or in environments where array internal representations may vary.Alternative Approaches
Other alternative approaches for accessing the last element of an array include:
at()
method (introduced in ECMAScript 2019): arr.at(-1)
It's worth noting that these alternatives may not be supported by older browsers or JavaScript engines.