var arr = Array.from(Array(100).keys());
arr.slice(-1);
arr[arr.length-1];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
`array.slice(-1)[0]` | |
`array[array.length-1]` |
Test name | Executions per second |
---|---|
`array.slice(-1)[0]` | 5970629.5 Ops/sec |
`array[array.length-1]` | 3631181.8 Ops/sec |
Let's break down the provided benchmark definition and explain what is being tested.
What is being tested?
The benchmark measures the performance of two ways to get the last item in an array: using array.slice(-1)[0]
or array[array.length - 1]
. The goal is to determine which method is faster.
Options compared
There are two options being compared:
array.slice(-1)[0]
: This method creates a new array with the last element and then extracts it using [0]
.array[array.length - 1]
: This method directly accesses the last element of the original array.Pros and Cons
array.slice(-1)[0]
:array[array.length - 1]
:Other considerations
lodash
(which provides a last()
method) could provide an alternative.Alternatives
If you wanted to create similar benchmarks for other scenarios, you could consider testing:
array[0]
, array.slice(0, 1)
)sort()
method vs. a custom comparison function)Keep in mind that the choice of benchmark scenario depends on your specific use case and goals.