Probe into the efficiency of for-loop in JavaScript and the related optimization _javascript techniques

Source: Internet
Author: User
Tags array length

Underscore.js Library

How many loops have you written in a day (week)?

var i;
for (i = 0; i < somearray.length i++) {
 var something = somearray[i];
 Dosomeworkon (something);
}

It's harmless, but it's very ugly and strange, and it's not really a complaint to be complaining about. But the wording 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're spreading bad code, and you're insane before you throw a whole bunch of if.
I haven't written a loop in two years.
"What are you talking about?" ”
It's true, a cold joke. Not really one of them (well, I did write a few), because I don't write loops (loops), my code is easier to understand.
How do you do that?

_.each (Somearray, function (something) {
 Dosomeworkon (something);
})

Or a little better:

_.each (Somearray, Dosomeworkon);

That's what Underscorejs did. Clean, simple, easy to read, short, no intermediate variables, no stacks of semicolons, simple, very elegant.
Here are some other examples.

var i, result
 = [];
for (i = 0; i < somearray.length i++) {
 var something = somearray[i];
 Hit here, I already have a hand ache.
 if (Something.isawesome = = True) {
   Result.push (somearray[i]);
 }


Similarly, a typical use case that uses a cycle to waste time. Even if the sites are for banning smoking and vegetarianism, I am outraged to see the code. Look at the simple wording.

var result = _.filter (Somearray, function (something) {return
 something.isawesome = = true;
})

Like the filter name in underscore, the 3 lines of code that you write can give you a new array.
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 sufficient in daily life, but these functions are not enough to let underscore on the table.

var grandtotal = 0,
 somepercentage = 1.07,
 severalnumbers = [n.,],
 I//don ' t forget to hoist those in dices;
for (i = 0; i < severalnumbers.length i++) {
 var anumber = severalnumbers[i];
 GrandTotal + + anumber * somepercentage;
}

Underscore version

var somepercentage = 1.07,
 severalnumbers = [A, n, a],
 grandtotal;
GrandTotal = _.reduce (severalnumbers, function (RunningTotal, anumber) {return
 runningtotal + (Anumber * somepercentage);
}, 0)

It may seem a little strange at first, I looked up the documentation about reduce and I knew it was there. Because I refuse to use the loop, so it's my first choice. These things are just getting started, and the Underscorejs Library has a ton of cow B functions.

30 days without the challenge of using loops.

In a next 30 days, do not use any loops, if you see a bunch of nasty and rough things, use each or map to replace them. Use a little reducing.

You need to note that underscore is leading to functional programming. A visible, invisible way. A good way to do it.


OURJS Note * Current browsers have supported each, filter, map, and reduce methods, but underscore libraries can be compatible with older versions of IE, and the following are examples of using ES5 native methods:

[3,4,5,3,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);  4 Cycles: 2-5 return
  pre + cur;  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

It has been proposed that for-in efficiency is much less efficient than for loop (loop). Now we're going to test how efficient it is for loop and foreach to work with large arrays in different browsers.

Most open source software currently caches array lengths in the For loop because the common view is that some browser Array.Length will recalculate the length of the array each time, so a temporary variable is usually used to store the array length beforehand, such as:

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

We will also test the performance difference between caching and not caching.

Add a summation operation to 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 caching and not caching.

Add a summation operation to 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 test data with large array of 2 million data var Testarray = [], Testobject = {}, idx, len = 2000000, tmp = 0,

 $results = $ ("#results"), $browser = $ ("#browser");
 $browser. HTML (navigator.useragent);

 $results. HTML (');
  number);
 Testobject[i] = number; $results. Append (' <tr><th> test code </th><th> calculation results </th><th> time required, Ms </th><

 /tr> ');

  Test function var test = function (TestFunc) {var starttime, endtime, result;
  StartTime = new Date ();
  TMP = 0;
  TestFunc ();

  Endtime = new Date ();
  Calculate the time required to run the test case (testing cases) = 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 for efficiency for in IDX in Testarray) {tmp + = Testarray[idx];///tested, IDX is a string type, probably one of the reasons for the Slow}}); Test (function () {///test efficiency for Loop loop for (idx = 0, len = testarray.length; idx < len; idx++) {tmp + Testarray[i
  DX];

 }
 });
  Test (function () {///Testarray.foreach efficiency of the ForEach (function (data) {tmp + = data;
 });

 });
  Test (function () {///test does not cache array.length efficiency for (idx = 0; idx < testarray.length; idx++) {tmp + = Testarray[idx];

 }
 });
  Test (function () {///test using {} (Object) to save the value pair, use for in to the efficiency of how to (idx in testobject) {tmp + TESTOBJECT[IDX];
 
 }
 });
   Test (function () {///test how efficient it is to check values from {} object (the key value is known beforehand) for (idx = 0, len = testarray.length; idx < len; idx++) {
  TMP + + TESTOBJECT[IDX];

}
 });

 }

Run [Wait a moment]
Test results
The test results may vary depending on the calculation, which is a summary of the test results that were run on my machine, Firefox, Chrome, ie.

Here are a few observed conclusions

    • For in is much slower than for loop, at least 20 times times slower in chrome
    • FF is optimized for foreach (ES5), performance is better than for loop, but Chrome/ien performance is poor
    • Ff/chrome Cache array.length are a bit slower than when they are directly available. It's very surprising that the performance improvement is negligible in addition to the latest version of IE cache
    • In some cases, FF's JS engine performance seems to be better than V8
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.