var arr = [1, 3, 5, 11, 13, 123, 123 ,32, 123, 23213, 2323, 2313, 545];
arr.slice(0, -1);
arr.pop();
arr.at(-1)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Slice | |
Pop | |
At(-1) |
Test name | Executions per second |
---|---|
Slice | 5676506.0 Ops/sec |
Pop | 9150129.0 Ops/sec |
At(-1) | 9059490.0 Ops/sec |
Let's break down the JavaScript microbenchmark on MeasureThat.net.
Benchmark Definition
The benchmark definition is a JSON object that defines the scope of the test. In this case, it only has a single property called "Script Preparation Code", which contains a JavaScript array arr
with 11 elements. The script preparation code sets up the array and makes it available for use in the subsequent benchmark definitions.
Individual Test Cases
The individual test cases are designed to measure the performance of three different ways to access the last element of the array:
arr.slice(0, -1)
. This method creates a new array that includes all elements up to but not including the last one.arr.pop()
. This method removes and returns the last element from the original array.arr.at(-1)
. This method is used in modern JavaScript versions (from ECMAScript 2020 onwards) to access an element at a specific index, where -1 refers to the last element.Options Compared
The benchmark compares the performance of these three methods:
at
method.Pros and Cons
Here are some pros and cons of each approach:
at
method.Other Considerations
at
method in modern JavaScript versions provides a convenient way to access elements at specific indices without modifying the original array.Alternative Approaches
Some alternative approaches could include:
indexOf
and slice
methods together: arr.slice(arr.indexOf(arr[arr.length - 1]))
. This approach avoids creating an extra array object but still has some overhead due to the use of indexOf
.var lastIndex = arr.length - 1; var lastElement = arr[lastIndex]
. This approach is simple and efficient but may not be suitable for all use cases.However, these alternative approaches are not included in the benchmark on MeasureThat.net, so their performance characteristics are not compared.