arr = Array.from({length: 1000}, (_, i) => i);
const index_zero = arr[0];
console.log(index_zero);
const index_random = arr[Math.floor(Math.random() * arr.length)];
console.log(index_random);
const index_last = arr[arr.length - 1];
console.log(index_last);
const at_zero = arr.at(0);
console.log(at_zero);
const at_random = arr.at(Math.floor(Math.random() * arr.length));
console.log(at_random);
const at_last = arr.at(-1);
console.log(at_last);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Initial value indexing | |
Random value indexing | |
Last value indexing | |
Initial value at() | |
Random value at() | |
Last value at() |
Test name | Executions per second |
---|---|
Initial value indexing | 459557.7 Ops/sec |
Random value indexing | 440218.0 Ops/sec |
Last value indexing | 245015.4 Ops/sec |
Initial value at() | 89233.0 Ops/sec |
Random value at() | 95650.5 Ops/sec |
Last value at() | 81549.8 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition
The benchmark definition is a JSON object that describes the test to be performed. In this case, it compares the performance of Array.prototype.at()
(the "at" method) with traditional indexing (using bracket notation, e.g., arr[i]
) for retrieving elements from an array.
Script Preparation Code
The script preparation code is a JavaScript snippet that creates an array of 1000 elements using Array.from()
and assigns it to the variable arr
.
Html Preparation Code
There is no HTML preparation code provided, which suggests that this benchmark focuses solely on JavaScript performance.
Individual Test Cases
The benchmark consists of six test cases, each with a unique scenario:
arr[0]
).arr[Math.floor(Math.random() * arr.length)]
).arr[arr.length - 1]
).Array.prototype.at(0)
.Array.prototype.at(Math.floor(Math.random() * arr.length))
.Array.prototype.at(-1)
.Library
In all test cases, no libraries are explicitly mentioned, but Array.from()
is used to create the array. This function is part of the ECMAScript standard and is supported by most modern browsers and Node.js environments.
Special JavaScript Features
The benchmark uses the following special JavaScript features:
Math.random()
: generates a random number between 0 (inclusive) and 1 (exclusive).Array.prototype.at()
: provides a more concise way to access elements in an array, similar to C-style indexing. This method was introduced in ECMAScript 2022.Pros and Cons of Different Approaches
Here's a brief analysis of the pros and cons of each approach:
arr[0]
):Other Alternatives
If you're interested in exploring alternative approaches or optimizations for this benchmark, consider the following:
slice()
or map()
instead of Array.from()
to create the array.Keep in mind that these alternatives might not significantly impact the benchmark's overall outcome but can help you better understand the trade-offs involved.