Javascript defines four types of loops: for, while, do-while, and for-in. The performance of the first three cycles is not much different, but the for-in loop performance is very poor. During each loop execution, it needs to traverse all the attributes in the object including those inherited from the prototype chain, as to how bad its performance is, the following is the test in Chrome18 (using YUI Profiler as an analysis tool, if it is not used to show the Javascript performance analysis I wrote earlier -- tool (YUI Profiler)) http://www.bkjia.com/kf/201204/126311.html:
// Array Length
Var loopCount = 20000000;
// Prepare the test Array
Var mockAry = new Array ();
For (var I = 0; I <loopCount; I ++ ){
MockAry. push (I );
}
// For Loop
Function testForAry (){
For (var I = 0; I <loopCount; I ++ ){
Var value = mockAry [I];
}
}
// While LOOP
Function testWhileAry (){
Var I = 0;
While (I <loopCount ){
Var value = mockAry [I];
I ++;
}
}
// Do-while loop
Function testDoWhileAry (){
Var I = 0;
Do {
Var value = mockAry [I];
I ++;
} While (I <loopCount );
}
// For-in Loop
Function testForInAry (){
For (var item in mockAry ){
Var value = item;
}
}
// Register the method to be tested
YAHOO. tool. Profiler. registerFunction ("testForAry", window );
YAHOO. tool. Profiler. registerFunction ("testWhileAry", window );
YAHOO. tool. Profiler. registerFunction ("testDoWhileAry", window );
YAHOO. tool. Profiler. registerFunction ("testForInAry", window );
// The number of times each test method is tested
Var testCount = 10;
For (var I = 0; I <testCount; I ++ ){
TestForAry ();
TestWhileAry ();
TestDoWhileAry ();
TestForInAry ();
}
// Generate Test report
Var report1 = YAHOO. tool. Profiler. getFunctionReport ("testForAry ");
Var report2 = YAHOO. tool. Profiler. getFunctionReport ("testWhileAry ");
Var report3 = YAHOO. tool. Profiler. getFunctionReport ("testDoWhileAry ");
Var report4 = YAHOO. tool. Profiler. getFunctionReport ("testForInAry ");
Console. log (report1 );
Console. log (report2 );
Console. log (report3 );
Console. log (report4 );
Test results:
It can be seen that do-while is slower than for and while, but it can be ignored, while for-in is really bad, which is about 100 times slower. In practice, this crazy loop is rarely encountered during testing, but you still need to pay attention to using the for-in loop as little as possible, but when traversing an object (rather than a simple array) the for-in loop is a good helper in high-performance JavaScript. It also introduces many techniques for improving loop traversal, which will be detailed later.
From Miser