In-depth exploration of efficiency issues and related optimization of the for Loop in JavaScript, javascriptfor

Source: Internet
Author: User

In-depth exploration of efficiency issues and related optimization of the for Loop in JavaScript, javascriptfor

Underscore. js Library

How many cycles have you written in one day (one week?

var i;for(i = 0; i < someArray.length; i++) { var someThing = someArray[i]; doSomeWorkOn(someThing);}

This is harmless, but it is ugly and strange, and it is not really a complaint. However, this writing method is too mediocre.

var i, j;for(i = 0; i < someArray.length; i++) { var someThing = someArray[i]; for(j = 0; j < someThing.stuff.length; j++) {   doSomeWorkOn(someThing.stuff[j]); }}

You are scaling out bad code, and you are already confused before you throw a lot of if.
I did not write a loop in two years ).
"What are you talking about ?"
This is a joke. Actually, none of them (well, I did write a few). Because I don't write loop (loops), my code is easier to understand.
How can this problem be solved?

_.each(someArray, function(someThing) { doSomeWorkOn(someThing);})

Or better:

_.each(someArray, doSomeWorkOn);

This is what underscorejs does. Clean, simple, easy to read, short, no intermediate variables, no piles of semicolons, simple and elegant.
This is another example.

Var I, result = []; for (I = 0; I <someArray. length; I ++) {var someThing = someArray [I]; // if (someThing. isAwesome = true) {result. push (someArray [I]);}

Similarly, a typical use case that uses loops to waste time. Even if these websites promote smoking bans and vegetarianism, I feel angry when I see the code. Let's look at the simple writing method.

var result = _.filter(someArray, function(someThing) { return someThing.isAwesome === true;})

Like the filter Name in underscore, the new array can be provided with three lines of code handwritten ).
Or do you want to convert these arrays into another form?

var result = _.map(someArray, function(someThing) { return trasformTheThing(someThing);})

The above three examples are enough in daily life, but these functions are insufficient to put underscore on the table.

var grandTotal = 0, somePercentage = 1.07, severalNumbers = [33, 54, 42], i; // don't forget to hoist those indices;for(i = 0; i < severalNumbers.length; i++) { var aNumber = severalNumbers[i]; grandTotal += aNumber * somePercentage;}

Underscore version

var somePercentage = 1.07, severalNumbers = [33, 54, 42], grandTotal;grandTotal = _.reduce(severalNumbers, function(runningTotal, aNumber) { return runningTotal + (aNumber * somePercentage);}, 0)

This may seem a bit strange at the beginning. I checked the reduce document and learned its existence. Because I refuse to use loops, it is my first choice. The above are just getting started. The underscorejs Library also has a lot of Functions of niub.

The challenge of not using loops for 30 days.

In the next 30 days, do not use any loops. If you see a bunch of annoying and rough things, replace them with each or map. Use a little more compaction.

You need to note that Underscore leads to functional programming. A visible and invisible way. A good way.


OurJS note * Currently, modern browsers support the each, filter, map, and reduce methods, but the underscore library can be compatible with older IE versions. Below is an example of using ES5 native method to write:

[3, 4, 5, 3]. forEach (function (obj) {console. log (obj) ;}); [1, 2, 3, 4, 5]. filter (function (obj) {return obj <3}); [9, 8, 5, 2, 3, 4, 5]. map (function (obj) {return obj + 2 ;}); [1, 2, 3, 4, 5]. reduce (function (pre, cur, idx, arr) {console. log (idx); // four loops: 2-5 return pre + cur;}); // 15 // The sort method is also useful [9, 8, 5, 2, 3, 4, 5]. sort (function (obj1, obj2) {return obj1-obj2 ;});

For in and for loop

Someone suggested that the efficiency of for in is much lower than that of for loop. Now let's test the efficiency of using for in, for loop, and forEach in different browsers in processing large arrays.

At present, most open-source software caches the Array length in the for loop, because some browsers generally think that Array. length recalculates the array length each time. Therefore, temporary variables are usually used to store the array length in advance, for example:

for (var idx = 0, len = testArray.length; idx < len; idx++) { //do sth.}

We will also test the performance difference between cache and non-cache.

At the same time, add the sum operation in each test loop to indicate that it is not an empty loop.

for (var idx = 0, len = testArray.length; idx < len; idx++) { //do sth.}

We will also test the performance difference between cache and non-cache.

At the same time, add the sum operation in each test loop to indicate that it is not an empty loop.

The test code is as follows. Click Run To View
HTML code

JavaScript code

Function () {// prepare the test data. A large array of 2 million pieces of data var testArray = [], testObject = {}, idx, len = 2000000, tmp = 0, $ results = $ ("# results"), $ browser = $ ("# browser"); browse browser.html (navigator. userAgent); Response results.html (''); for (var I = 0; I <len; I ++) {var number = Math. random (); // if you want to speed up the operation, use the integer: Math. random () * 10 | 0 testArray. push (number); testObject [I] = number;} $ results. append ('<tr> <th> test code </th> <th> calculation result </th> <th> time required, millisecond </th> </tr> '); // test the function var test = function (testFunc) {var startTime, endTime, result; startTime = new Date (); tmp = 0; testFunc (); endTime = new Date (); // time required for running a Test Case result = endTime-startTime; $ results. append ('<tr> <td> <pre> {0} </pre> </td> <td> {1} </td> <td> {2} </td> </tr> '. format (testFunc. toString (), tmp | 0, result) ;}; test (function () {// test the efficiency of for in for (idx in testArray) {tmp + = testArray [idx]; // tested, idx is of the string type and may be one of the reasons for slowness}); test (function () {// test the efficiency of the for loop (idx = 0, len = testArray. length; idx <len; idx ++) {tmp + = testArray [idx] ;}}); test (function () {// test the efficiency of forEach testArray. forEach (function (data) {tmp + = data;}) ;}); test (function () {// The test does not cache the Array. length aging rate for (idx = 0; idx <testArray. length; idx ++) {tmp + = testArray [idx] ;}}); when the test (function () {// test using the {} (Object) health value pair, how is the efficiency of using for in? for (idx in testObject) {tmp + = testObject [idx] ;}}); test (function () {// test the efficiency of checking values from {} Object (the key value here is known in advance) for (idx = 0, len = testArray. length; idx <len; idx ++) {tmp + = testObject [idx] ;}});}

Run [Wait a moment]
Test Results
The test results may vary by calculation. This is a summary of the test results of Firefox, Chrome, and IE running on my machine.

The following are several observations:

  • For in is much slower than for loop, and at least 20 times slower in Chrome
  • FF has optimized forEach (ES5) to provide better performance than for loop, but Chrome/IEn has poor performance.
  • FF/Chrome cache Array. length is a little slower than the direct time. Except for the latest version of IE, the cache performance is slightly improved (this is very surprising)
  • In some cases, FF's JS engine seems to have better performance than V8
Articles you may be interested in:
  • Summary of methods for looping through Array and Map in JavaScript
  • Javascript to implement label jumping out of the loop
  • Understanding how Map replaces loops in javascript
  • A daily required cycle of javascript
  • Example of three Javascript loop keywords (for and while)
  • JavaScript code for implementing asynchronous Loops
  • Implement waterfall stream Effect Based on JavaScript (cyclical)
  • High-performance JavaScript loop statements and condition statements
  • Javascript image switching comprehensive instance (Cyclic switching and sequential switching)
  • Understanding JS event Loops

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.