var testingArray = new Array(1000).fill(1);
const newArr = [];
for (let i = 0, item; (item = testingArray[i]); i += 1) {
newArr.push(item);
}
const newArr = [];
for (const item of testingArray) {
newArr.push(item);
}
const newArr = [];
testingArray.forEach(item => {
newArr.push(item);
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For i | |
For of | |
ForEach |
Test name | Executions per second |
---|---|
For i | 10608.9 Ops/sec |
For of | 184306.3 Ops/sec |
ForEach | 148914.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
What is being tested?
MeasureThat.net provides a platform for users to create and run JavaScript microbenchmarks. In this case, we're interested in understanding what options are compared, their pros and cons, and other considerations when it comes to iterating over arrays using for
, for...of
, and forEach
.
The benchmark definition JSON provides the following information:
Options being compared
The three test cases are designed to compare different approaches for iterating over arrays:
for
loop to iterate over the array, where the loop variable is declared and updated manually.for...of
loop, which allows for more concise and readable code for iterating over arrays.forEach
method, which is a part of the Array prototype and provides a more functional programming-style way to iterate over arrays.Pros and cons of each approach
Here's a brief summary of the pros and cons of each approach:
for...of
loopforEach
methodLibrary used:
In this benchmark, there is no explicit library mentioned. However, it's worth noting that some browsers may have internal optimizations or extensions that could affect performance. For example, modern browsers like Chrome and Firefox have built-in support for for...of
loops and forEach
methods.
Special JS feature or syntax:
There are no special JavaScript features or syntax used in this benchmark. The focus is on the iteration mechanisms (looping and array methods) rather than any specific language features.
Other alternatives:
If you're interested in exploring alternative approaches, here are a few options:
true
if all elements pass the test.true
if at least one element passes the test.function
declarations.Keep in mind that these alternatives may not directly address the same iteration concerns as the original benchmark, but they do offer alternative approaches for working with arrays.