Comparison of for and each performance and foreach Performance
<! DOCTYPE html>
<Html>
<Head>
<Meta charset = "UTF-8">
<Title> for and each performance comparison </title>
</Head>
<Body>
<Div id = "test"> </div>
<Input type = "button" value = "for" onclick = "getFor ();"/>
<Input type = "button" value = "each" onclick = "getEach ();"/>
<Script type = "text/javascript" src = "http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"> </script>
<Script type = "text/javascript" language = "javascript">
$ (Function (){
// Add data
For (var I = 0; I <200; I ++ ){
$ ("# Test"). append ('<div class = "test" title = ""> test </div> ');
}
});
Function getFor (){
Var getclass = $ (". test ");
Var length = getclass. length;
Console. log (length );
Var timestart = new Date (). getTime ();
For (var I = 0; I <length; I ++ ){
Getclass [I]. title = 'I am ';
}
Var timeend = new Date (). getTime ();
Alert ("for time consumption:" + (timeend-timestart ));
}
Function getEach (){
Var timestart = new Date (). getTime ();
$ (". Test"). each (function (){
$ (This). attr ('title', 'mybackback ');
});
Var timeend = new Date (). getTime ();
Alert ("each time consumed:" + (timeend-timestart ));
}
</Script>
</Body>
</Html>