As one of the three logic control structures of program language, loop is often encountered in actual development. We often encounter this application in the use of the looping structure of JavaScript programs. Loops on the length of an object and processes each element of the object.
As
for (Var i=0;i<a.length;i++) {
Sum+=a[i]
}
This is just a simple example of how many program developers have studied the effectiveness of their execution as a program. So there are two ways to do this:
for (Var i=0,ilen=a.length;i<ilen;i++) {
Sum+=a[i]
}
for (Var i=0,item;item=a[i];i++) {
Sum+=item;
}
Or
for (var I=0,item; (Item=a[i])!=undefined;i++) {
Sum+=item;
}
How much difference does the performance of three kinds of writing have? Which is more efficient? I tested it on my own machine: it was found that under 10,000 data, the speed difference between the three is not small, the difference is about 0.01m, and the test results are unstable.
Then the data into 50w to test: Three methods of test results are:
1182
981
1673 (and prompts for "slow program execution, canceling the script")
1572
1462
12067 (same hint of slow script loading)
Although the data is not very stable, there is still something to be found.
The quickest way to do this is to save the length of the object and avoid calculating it every time. The slowest is the third way of writing: the length of an object that does not relate to it, and whether the current item is present or not. I always thought it was the third one. The speed should be the fastest (since no length is used), and it appears that the third kind of execution efficiency is so low that it seems to be avoided. Of course, many times we may have to use this third way of writing.
The test procedures are as follows: (we recommend that three programs be tested separately, especially under FF)
<script type= "Text/javascript" >
<!--
var a=[];
for (Var i=0;i<500000;i++) {
A.push (100);
}
var sum=0;
var timer1=new Date (). GetTime ();
for (Var i=0;i<a.length;i++) {
Sum+=a[i];
}
Alert (sum+ "\ntime:" + (New Date (). GetTime ()-timer1));
sum=0;
var timer2=new Date (). GetTime ();
for (Var i=0,ilen=a.length;i<ilen;i++) {
Sum+=a[i];
}
Alert (sum+ "\ntime:" + (New Date (). GetTime ()-timer2));
sum=0;
var timer3=new Date (). GetTime ();
for (Var i=0,item;item=a[i];i++) {
Sum+=item;
}
Alert (sum+ "\ntime:" + (New Date (). GetTime ()-timer3));
-->
</script>