arr = Array(10000).fill().map(x=>Math.random())
arr.map(x=>{});
arr.forEach(x=>{});
for(let i = 0;i<arr.length;i++){let x=arr[i]}
for(let x of arr){}
for(let i of arr.keys()){let x = arr[i]}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
.map | |
.forEach | |
for loop | |
for of loop | |
for of keys |
Test name | Executions per second |
---|---|
.map | 1228.9 Ops/sec |
.forEach | 1508.7 Ops/sec |
for loop | 89.7 Ops/sec |
for of loop | 10460.1 Ops/sec |
for of keys | 175.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition
The provided JSON represents a benchmark definition for measuring the performance of different looping constructs in JavaScript. The script preparation code creates an array of 10,000 random numbers using the Array.prototype.fill()
and Array.prototype.map()
methods. This ensures that all tests have the same input data, allowing for fair comparisons.
Options Compared
The benchmark compares four different looping constructs:
for
statement.Array.prototype.forEach()
method, which calls a provided callback function for each element in the array.Array.prototype.map()
method, which returns a new array with the results of applying a provided transformation function to each element in the original array.Pros and Cons
Here's a brief summary of the pros and cons of each looping construct:
Other Considerations
When evaluating the performance of these looping constructs, it's essential to consider factors like:
Libraries and Special Features
No libraries are used in this benchmark. However, if a test case uses an external library, it's essential to consider the performance impact of that library on the overall benchmark result.
If a test case includes special JavaScript features like async/await
, promises
, or genurescript
, these should be carefully evaluated and potentially excluded from the benchmark results to ensure fairness and relevance.
Alternatives
For those interested in exploring alternative looping constructs, some notable options include:
Keep in mind that these alternatives might introduce additional dependencies, overhead, or complexity to your benchmarking setup.