As a front-end developer, for and foreach loop traversals are used almost every day, so which of these two traversals is more efficient? What is the reason for this high efficiency?

A for() loop

Iterate over the code in the loop with subscripts, which are powerful enough to get elements via index. It is more convenient when dealing with more complex processing

ForEach () loop

The forEach() method is used to call each element of the array and pass the element to the callback function. Foreach is also called an enhanced for loop. Foreach is a special, simplified version of the for loop. Note that forEach() does not perform callbacks on empty arrays

array.forEach(function(currentValue, index, arr), thisValue)Copy the code

Function (currentValue, index, arr) : required. The function to be called for each element in the array.

currentValue Required, current element

index

Optional, index value of the current element.

arr Optional, the array object to which the current element belongs.

ThisValue: Optional. The value passed to the function is usually the “this” value. If this parameter is empty, “undefined” is passed to the value “this”

Console. time and console.timeEnd

Console. time and console.timeEnd are two methods that allow WEB developers to measure how long a javascript script takes to execute. As WEB applications become more important and JavaScript performance becomes more important, WEB developers know that some performance testing machine is a must. There are many ways to test the performance of JavaScript but console. The time/console timeEnd two methods is the most basic, the most direct technique.

  1. The console.time method is used to start calculating the time
  2. Console. timeEnd stops the timer and outputs the script execution time.
  3. In either case, you can pass in a parameter as the name of the timer, which is used to keep track of the timers when the code runs in parallel.
  4. rightconsole.timeEndThe call immediately outputs the total execution time in milliseconds.

// Start the timer
console.time('Timer name');

// Write some test code.

// Stop the timer, output time
console.timeEnd('Timer name');
Copy the code

Four, test performance

At the 1000000 level, forEach performs better than for

let arrs = new Array(1000000);

console.time('for');
for (let i = 0; i < arrs.length; i++) {};
console.timeEnd('for'); / / for: 10.329833984375 ms

console.time('forEach');
arrs.forEach((arr) = > {});
console.timeEnd('forEach'); / / forEach: 5.076904296875 msCopy the code

At the level of 10000000, the performance of forEach is still higher than for

let arrs = new Array(10000000);

console.time('for');
for (let i = 0; i < arrs.length; i++) {};
console.timeEnd('for'); / / for: 95.157958984375 ms

console.time('forEach');
arrs.forEach((arr) = > {});
console.timeEnd('forEach'); / / forEach: 37.9619140625 msCopy the code

At levels above 100 million, the performance of forEach is significantly lower than that of for

let arrs = new Array(100000000);

console.time('for');
for (let i = 0; i < arrs.length; i++) {};
console.timeEnd('for'); / / for: 939.18994140625 ms

console.time('forEach');
arrs.forEach((arr) = > {});
console.timeEnd('forEach'); / / forEach: 1614.8642578125 msCopy the code

5. For and forEach

[3.1] Traversal

The for loop iterates sequentially, while forEach iterates using the iterator

[3.2] Data structure

A for loop is a random access element, and a foreach is a sequential list access element

[3.3] Performance

For an ArrayList, which is a sequential list, the for loop can be accessed sequentially, which is faster. Using foreach is slightly slower than the for loop. For linkedlist, which is a singly linkedlist, the for loop reads the next field from the first element each time, which is very slow; Using foreach, you can read the current node directly, and the data is faster.

Six, how to choose

Foreach has less code than for loops, but Foreach relies on IEnumerable. Runs less efficiently than the for loop. Of course, if you’re dealing with a loop with an indeterminate number of cycles, or if the number of cycles needs to be calculated. Using Foreach is convenient. And the foreach code is optimized by the compilation system to be similar to the for loop.

Foreach is a special, simplified version of the for statement. Foreach provides developers with great convenience in iterating through groups of numbers and collections. When designing complex loops, you should still use the for loop for more flexibility.


The article is updated every week. You can search “Front-end highlights” on wechat to read it in the first time, and reply to [Books] to get 200G video materials and 30 PDF books