var data = [Array(100000).keys()]
var d = data[data.length - 1]
var z = data.at(-1)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
1 | |
2 |
Test name | Executions per second |
---|---|
1 | 151873200.0 Ops/sec |
2 | 151175328.0 Ops/sec |
Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The provided JSON represents a benchmark test case, which compares two approaches for accessing the last element of an array in JavaScript: using square bracket notation (array[0]
) versus Array.prototype.at(0)
.
Benchmark Definition
The benchmark definition is:
data
. The keys of this array are generated using the spread operator (...
) and the Array
constructor.Individual Test Cases
The benchmark consists of two test cases:
data
array using square bracket notation (array[0]
).data
array using the Array.prototype.at()
method.Pros and Cons
array[0]
):Array.prototype.at()
method due to its nature of accessing elements at a specific index, even if the array is not fully populated.Array.prototype.at(0)
Method:Library/Functionality
Array.prototype.at()
Method:Special JS Feature/Syntax
Other Alternatives
For accessing the last element of an array, other alternatives include:
Math.max()
and the spread operator (...
): var d = Math.max(...data)
var d; for (const i of data) { d = i; break; }
However, these alternatives may not be as efficient or concise as using square bracket notation (array[0]
) or the Array.prototype.at()
method.
Benchmark Preparation Code
The provided benchmark preparation code creates a large array with 100,000 elements and assigns it to the variable data
. This ensures that both test cases have access to a large dataset for comparison.