var arr = [];
for (var i = 0; i < 1000; i++) {
arr[i] = i;
}
function someFn(i) {
return i * 3 * 8;
}
arr.forEach(someFn)
for (var i = 0, len = arr.length; i < len; i++) {
someFn(arr[i]);
}
arr.map(item => someFn(item))
for (const i of arr) {
someFn(arr[i]);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for | |
map | |
for of |
Test name | Executions per second |
---|---|
foreach | 187817.5 Ops/sec |
for | 17876.2 Ops/sec |
map | 34336.8 Ops/sec |
for of | 17592.5 Ops/sec |
Let's break down the provided benchmark and its test cases.
What is being tested?
The provided JSON represents a JavaScript microbenchmarking test case on MeasureThat.net. The main focus of this benchmark is to compare the performance of different iteration methods in JavaScript: Array forEach()
, traditional for
loop, Array.prototype.map()
method, and an arrow function-based for...of
loop.
Options compared
The four options being compared are:
forEach()
: This method calls a provided callback function once for each element in the array, allowing it to be used as an iterator.for
loop: A classic loop structure that manually increments a counter and accesses elements of an array using their index.Array.prototype.map()
method: A method that creates a new array with the results of applying a provided function on every element in this array.for...of
loop: An alternative syntax for iterating over arrays, introduced in ECMAScript 2015 (ES6).Pros and Cons
forEach()
:for
loop:Array.prototype.map()
method:for
loops due to compiler optimizations.for...of
loop:for
loops, allows for the use of arrow functions, and is often faster due to compiler optimizations.Library and syntax
The provided test cases use the following libraries and syntax:
for...of
loop introduced in ECMAScript 2015 (ES6).Alternatives
If you're looking for alternative benchmarking tools or approaches, consider the following:
benchmark.js
or fastify-benchmark
, which provide a more structured approach to writing and running benchmarks.In conclusion, the provided MeasureThat.net benchmark provides a simple and concise way to compare the performance of different iteration methods in JavaScript. By understanding the pros and cons of each option, developers can make informed decisions about which approach best suits their use case.