This is the sixth day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
The difference between for and forEach —– do you understand the following?
Foreach is one of the most commonly used attributes, but today we encountered some problems and found that the understanding of this is not enough, so let’s summarize the differences between for and foreach.
Previously, I thought that the difference between for and forEach was mainly in syntax and performance, but today I suddenly found that return and break could not end the forEach loop.
Break out of the loop
Foreach: break ();
2. Foreach uses a return to terminate execution, rather than terminate the loop, similar to a continue in a for loop. Foreach does not return a value
So foreach breaks out of the loop as follows:
throw new Error("End");
Copy the code
This will solve the problem of breaking out of the loop, but the console will generate an error and say try catch.
Second, the performance
In terms of performance
let arrs = new Array(100000);
console.time('for');
for (let i = 0; i < arrs.length; i++) {
};
console.timeEnd('for');
console.time('forEach');
arrs.forEach((arr) = >{});console.timeEnd('forEach');
for: 2.263ms
forEach: 0.254ms
Copy the code
At the 100,000 level, forEach is ten times better than for
for: 2.263ms
forEach: 0.254ms
Copy the code
On the order of 1 million, forEach performs as well as for
for: 2.844ms
forEach: 2.652ms
Copy the code
At levels above 10 million, the performance of forEach is much lower than that of for
for: 8.422ms
forEach: 30.328m
Copy the code
After the actual test, on different computers, the division of weight is different, but the general classification trend is the above, when the amount of data is small, the performance of forEach will be better, on my machine, about 30,000 forEach is better, when the amount of data is greater than 30,000, there is no winner.
I don’t need to talk about the grammar, I think we all know.