Which do you know for Loops or iterators fit the requirements , Can avoid making some low-level mistakes , And then the application performance is reduced .

Javascript yes web A new experience of development . It's not just like NodeJS、React、Angular、Vue etc. JS frame . however ,vanilla JS There's also a huge fan base . Loops have always been an important part of most programming languages . newest Javascript There are many ways to iterate and loop .

But the problem is , Whether you really know which loop or iteration performs best . There are a lot of for The cycle is optional ,forfor( The reverse )for...offorEach. Now let's understand one by one .

const million = 1000000;
const arr = Array(million);
// for( The reverse )
console.time("for( The reverse ) ");
for (let i = arr.length; i > 0; i--) {}
console.timeEnd("for( The reverse ) ");
// for( positive sequence )
console.time("for( positive sequence ) ");
for (let i = 0, len = arr.length; i < len; i++) {}
console.timeEnd("for( positive sequence ) ");
// for( positive sequence 2)
console.time("for( positive sequence 2) ");
for (let i = 0; i < arr.length; i++) {}
console.timeEnd("for( positive sequence 2) ");
// forEach
console.time("forEach ");
arr.forEach((v) => v);
console.timeEnd("forEach ");
// for...of
console.time("for...of ");
for (const v of arr) {
}
console.timeEnd("for...of ");

The results after running are as follows :

for( The reverse ) : 3.375ms
for( positive sequence ) : 2.592ms
for( positive sequence 2) : 2.259ms
forEach : 4.149ms
for...of : 24.111ms

summary :for( positive sequence ) and for( The reverse ) The cycle time is less than 1 millisecond . In reverse order for Loop the starting variable let i = arr.length, stay for( positive sequence ) In circulation , Every time I check i < arr.length The inspection conditions of , So from the results of implementation for( positive sequence 2) Less i < arr.length My judgment is that it can significantly improve efficiency .

So I'm writing for In the cycle , It should be reduced i < arr.length Similar judgments

forEach It's an array prototype method , It's quite normal for loop ,forEach and for…of More iterations for arrays .

Use occasion

for loop ( Positive and negative order )

Everyone is familiar with this cycle , Basically use it where it needs to be recycled for, Run duplicate blocks of code , It's tradition for The fastest in the loop . Sometimes performance is not the only standard to use , Code readability also needs to be considered , So it's the default paradigm .

forEach

Accept the callback function as the input parameter , And for each element in the array , Will execute this callback function .forEach The callback function accepts the current value and the corresponding index .h Again , allow this Use optional arguments in callback functions .

const array = ["dev", "point", "coding"];
const forCallback = (item, index) => {
    console.log(`${item} : ${index}`);
};
array.forEach(forCallback);

Running results :

dev : 0
point : 1
coding : 2

Be careful : If you use forEach, You can't use Javascript Short circuit function in ( When in Javascript Use in && or || When such a logical operator , It will help us terminate and / or skip iterations of the loop ahead of time ).

for…of

for…of stay ES6(ECMAScript 6) Has been standardized in . for…of Used to create an object that can be iterated over ( Such as arrays 、 mapping 、 aggregate 、 String, etc. ) The loop of the upper iteration . Another advantage of this loop is better readability .

const arrNumbers = [1, 3, 5];
const arrChats = "devpoint";
console.info("==>arrNumbers");
for (let i of arrNumbers) {
    console.log(i);
}
console.info("==>arrChats");
for (let i of arrChats) {
    console.log(i);
}

Be careful : Even if for...of Early termination , And don't reuse it on generators . After exiting the loop , The generator will close , And trying to repeat the generator again will not produce further results .

Conclusion

  • for The fastest , Readability is almost
  • forEach Fast , Controllable iteration properties
  • for...of slow , More convenient
  • for...in slow , inconvenient .

Last , Although efficiency is important , But in project development , Consider the readability of the code first . Because in complex application development , Code readability is more important than performance , Avoid unnecessary embellishments .