var array = [1, 2, 3];
function last1(array) {
return array[array.length - 1]
}
function last2(array) {
return array.at(-1)
}
var d = array[array.length - 1];
var z = array.at(-1);
var x = last1(array);
var y = last2(array);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array[array.length - 1] | |
array.at(-1) | |
array[array.length - 1] fn | |
array.at(-1) fn |
Test name | Executions per second |
---|---|
array[array.length - 1] | 456637088.0 Ops/sec |
array.at(-1) | 483425184.0 Ops/sec |
array[array.length - 1] fn | 427288032.0 Ops/sec |
array.at(-1) fn | 394820736.0 Ops/sec |
The benchmark presented tests the performance of two different methods for retrieving the last element of an array in JavaScript. This is performed through two direct methods of accessing the last element and two corresponding functions that wrap these methods.
Direct Access via Indexing:
array[array.length - 1]
Using the at()
Method:
array.at(-1)
at()
method is a built-in JavaScript method introduced in ES2022 that allows you to access elements in the array using negative integers, where -1
references the last element.Additionally, the benchmark tests functions that encapsulate these methods:
last1(array)
calls the first method (array[array.length - 1]
).last2(array)
calls the second method (array.at(-1)
).Each of the methods and their corresponding function wrappers is tested, and the performance is measured in terms of Executions Per Second (EPS). The results show the number of times each test can be executed within a second.
last1(array)
: 134,701,488 EPSarray[array.length - 1]
: 131,060,624 EPSlast2(array)
: 38,496,756 EPSarray.at(-1)
: 37,834,628 EPSDirect Indexing (array[array.length - 1]
):
Using at()
Method (array.at(-1)
):
Browser Compatibility: While array.at()
is part of the ECMAScript standard and supported in modern browsers, developers must consider compatibility with older browsers that might not support ES2022 features.
Code Readability: The choice between using direct indexing versus at()
might depend on the team's code style preference and the desire for clarity versus performance.
Lodash Library: A utility library that offers various array manipulation features, including functions like .last()
that can retrieve the last element of an array. A potential usage would be _.last(array)
, which can also improve readability but usually comes with more overhead from the library itself.
Custom Helper Functions: Developers can create custom utility functions tailored to their specific application needs. However, care should be taken to ensure that they optimize performance and maintain readability.
This benchmark is a straightforward illustration of choosing the best approach based on both performance and developer experience. By understanding the differences and performance characteristics of these methods, engineers can make informed choices in their JavaScript applications.