var arr = Array.from(Array(100).keys());
var last = arr.slice(-1)[0]
var last = arr[arr.length-1]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using slice | |
Using length |
Test name | Executions per second |
---|---|
Using slice | 10397922.0 Ops/sec |
Using length | 8373152.0 Ops/sec |
Let's dive into the benchmarking results.
What is being tested?
The provided JSON represents a benchmark test case that compares two different approaches to accessing the last element of an array:
slice(-1)[0]
arr.length-1
and indexing into the array directlyWhat options are compared?
Two JavaScript methods are being compared:
slice(-1)[0]
This approach uses the slice()
method to create a shallow copy of the last element from the original array. The -1
argument tells slice()
to start at the end of the array and return one element.
Example code:
var arr = Array.from(Array(100).keys());
var last = arr.slice(-1)[0];
arr.length-1
This approach directly accesses the length property of the array and subtracts 1 to get the index of the last element. Then, it uses that index to access the corresponding value in the array.
Example code:
var arr = Array.from(Array(100).keys());
var last = arr[arr.length-1];
Pros/Cons of each approach:
Pros:
Cons:
Pros:
Cons:
Other considerations:
Both methods are generally efficient, but the difference in performance lies in the overhead of creating an additional array copy using slice()
. The results suggest that directly accessing the last element using arr.length-1
is faster than using slice()
.
Library or special JS feature usage:
None in this benchmark.
Other alternatives:
pop()
method to remove and return the last element of an array. This approach is not shown in the provided test case but is another valid way to access the last element.var arr = Array.from(Array(100).keys());
var last = arr.pop();
This method has its own pros and cons, such as modifying the original array (if you don't want to remove the last element) or requiring additional handling for edge cases.
Keep in mind that this benchmark is focused on a specific scenario (accessing the last element of an array), so these alternatives might not be directly comparable.