Loop comparison and performance analysis in JS (handwritten forEach and Symbol.iterator)

Directory

Loop in JS:

for and while

Usage of for and while:

The performance of for and while:

forEach

The usage of forEach:

Handwritten forEach method:

Performance of forEach:

for in

The usage of for in:

Performance of for in:

for of

iterator iterator:

Symbol.iterator property of handwritten array:

usage of for

performance of for

Summarize

appendix

source code:

output result:


Loop in JS:

  • for and while
  • forEach
  • for in
  • for of

for and while

for loop and while control the loop process by yourself

for and while usage:

Usage of

//for
for (var i = 0; i < arr. length; i + + ) { }

Usage of

//while
let i = 1;
while(i < arr. length){
    i + + ;
}

for and while performance:

The performance of for and while is best among the five looping methods, and the performance of for and while is similar, so we can approximate them Same performance.

forEach

forEach is an iteration method provided by arrays in js, which can loop through each item of the array.

forEach usage:

//forEach usage
arr.forEach((item, index) => {
    //doSomeing
})

handwritten forEach method:

//forEach method of handwritten array
Array.prototype.forEach = function forEach(callback, context) {
    // this -> arr instance
    let self = this,
        i = 0,
        len = self. length;
    context == null ? window : context;
    for (; i < len; i ++ ) {
        typeof callback === "function" ? callback. call(context, self[i], i) : null;
    }
};

forEach performance:

The performance of forEach is second only to for and while among the five loop methods, and the performance is better.

for in

for in iterates objects: for in will iterate all enumerable properties of the current object (including private properties > and shared properties), will iterate over all properties on the prototype chain

There are many problems with for in:

  • Symbol properties cannot be iterated
  • The iteration order will take precedence over numeric attributes
  • Public enumerable {generally custom properties} properties will also be iterated

for in usage:

Usage of

//for in
for (let item in arr) { }

performance for in:

The performance of for in is terribly bad! Because for in will iterate over all enumerable properties of the current object (including private properties and shared Attribute), according to the prototype chain one-level search consumes a lot of performance.

(It can be found that the performance consumption of for in is hundreds or even thousands of times of other loop methods!)

for of

The principle of the for of cycle is to traverse according to the iterator specification

Only objects with iterator specification can use for of!

iterator iterator:

Iterator specification: The existence of Symbol.iterator property in an object means having iterator specification.

Objects with Symbol.iterator property:

  • array
  • partial class array
  • string
  • Set/Map data structure

For pure objects or self-created array-like objects, the default is does not have the property Symbol.iterator, so they do not have Iterator specification. (You cannot use the for of loop directly)

Symbol.iterator property of handwritten array:

//Symbol.iterator property of handwritten array
arr[Symbol. iterator] = function () {
    let self = this,
        index = 0;
    return {
        // must have the next method, execute the next method once, and get the value of a certain item in the structure
        // done: false value: the value obtained each time
        next() {
            if (index > self. length - 1) {
                return {
                    done: true,
                    value: undefined
                };
            }
            return {
                done: false,
                value: self[index + + ]
            };
        }
    };
};

If you want to perform a for of loop on an array-like object, just add the Symbol.iterator property to the array-like object strong> can:

 const obj = {
    0: 'a',
    1: 'b',
    2: 'c',
    3: 'd',
    4: 'e',
    length: 5
}

obj[Symbol.iterator] = Array.prototype[Symbol.iterator];

for (let i of obj) {
    console. log(i);
}

// output:
a
b
c
d
e

Usage of for of

Usage of

//for of
for (let item of arr) { }

for of performance

The performance of for of is slightly worse than that of forEach, but it is far better than that of for in.

Summary

for, while, forEach, for in, for of The performance ranking of the five loop methods is as follows:

for ≈ while > forEach > for of > for in

They have their own advantages and disadvantages and their respective application scenarios, use as needed.

Appendix

Source Code:

//An empty array with a length of 9999999, an array with empty objects is called a sparse array
// Some array methods cannot be used for sparse arrays
let arr = new Array(9999999);
//Output undefined
console.log(arr[0]);
//Fill 0 to sparse array 33
arr. fill(0)
// output 0
console.log(arr[0]);

//for
console.time('FOR~');
for (var i = 0; i < arr. length; i ++ ) { }
console. timeEnd('FOR~')

//while
console.time('WHILE~');
var i = 0;
while (i < arr. length) {
    i + +
}
console. timeEnd('WHILE~')

//forEach
console.time('FOREACH~');
arr.forEach((item) => {})
console.timeEnd('FOREACH~')

//for in
console.time('FORIN~');
for (let item in arr) { }
console. timeEnd('FORIN~')

//for of
console.time('FOROF~');
for (let item of arr) { }
console.timeEnd('FOROF~')

Output result: