function generateTestArray() {
const arr = [Array(50000).keys()];
return arr;
}
const array = generateTestArray();
console.time("for");
for(let i=0; i<array.length; i++) {}
console.time("for end");
const array = generateTestArray();
console.time("foreach");
array.forEach(value=>{});
console.time("foreach end");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for loop | |
foreach loop |
Test name | Executions per second |
---|---|
for loop | 50750.0 Ops/sec |
foreach loop | 53120.9 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
The provided JSON represents a benchmark that compares the performance of two different approaches for iterating over an array: foreach
(also known as forEach
) and a traditional for
loop.
What is being tested?
In this test, we're measuring how many iterations (or "executions") can be performed per second on an array containing 50,000 elements. The goal is to see which approach is faster: using foreach
or a for
loop.
Options compared:
forEach
): This is a built-in JavaScript method that allows you to iterate over an array and execute a function for each element.for
statement with a counter variable (i
).Pros/Cons:
for
loop can be optimized for performance by using techniques like cache blocking or parallelization (if applicable).for
loop requires more lines of code and can make your script harder to read.Other considerations:
foreach
method is a built-in JavaScript feature, introduced in ECMAScript 5 (2009).map()
, filter()
, or even recursion.Library explanation:
In this case, no external library is used, so there's nothing to explain here.
JavaScript feature or syntax explanation:
The foreach
method is a simple way to iterate over an array and execute a function for each element. It takes two arguments:
array
: The array you want to iterate over.callback
: A function that will be executed for each element in the array.Example:
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => {
console.log(number);
});
In this example, the forEach
method iterates over the numbers
array and executes a callback function for each element. The output will be:
1
2
3
4
5