One. Three array replication methods
1. by slice
var arr = [1, 2, 3], Copyarr;
Copyarr = Arr.slice ();
2. by concat
var arr = [1, 2, 3], Copyarr;
Copyarr = Arr.concat ();
3. by Loop
var arr = [1, 2, 3], Copyarr = [];
for (Var i=0, j=arr.length I
two. Test Environment
Browser: ie6+, FF 3.5.5, Opera, Chrome 4.0.249, Safari 4.0.3
Three. The trial example
uses the above 3 methods to copy an array that has 500000 items and then compare the time spent by the 3 methods.
<! DOCTYPE html> <ptml> <pead> <meta http-equiv= "Content-type" content= "text/html"; charset=gb18030 "/> <title>3 Array Replication method Performance comparison </title> <meta name=" description "content=" Array replication, slice, Concat "/> <meta name=" keywords "content=" array replication, slice, concat "/> </pead> <body> <div class=" s ection > <p> We use an array of 500,000 subkeys as the test object (ie will not crash!). </p> <button id= "J_copybyslice" >copyBySlice</button> <button id= "J_copybyconcat" >COPYBYC oncat</button> <button id= "J_copybyloop" >copyByLoop</button> </div> <script type= "text/j Avascript "> (function () {var arr = []; for (var i=0; i<500000; i++) {Arr.push (i); var get = function (ID) {return document.getElementById (ID); }; var byslice = function () {return arr.slice (); }; var byconcat = function () {return arr.concat (); }; VAr byloop = function () {var newArr = []; For (var i=0, j=arr.length; i<j; i++) {Newarr.push (arr[i)); return NEWARR; }; var showresult = function (Way, EL) {var st = +new Date (), omsg, NEWARR; Switch (way) {case ' slice ': NewArr = Byslice (); Break Case ' concat ': NEWARR = Byconcat (); Break Case ' Split ': NEWARR = Bysplit (); Break Case ' Loop ': NewArr = Byloop (); Break } omsg = document.createelement (' P '); omsg.innerhtml = ' Copy by ' + Way + ' use time: ' + (+new Date ()-st) + ' MS '; El.parentNode.appendChild (OMSG); }; Get (' J_copybyslice '). onclick = function () {Showresult (' slice ', this); } get (' J_copybyconcat '). OnClick = function () {showresult (' concat ', this); (' J_copybyloop '). onclick = function () {Showresult (' Loop ', this); } })(); </script> </body> </ptml>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
Four. Test results (click picture to view larger image)
Five. Conclusion
for IE, use slice; non ie, use concat.
For WebKit, use concat; Other browsers, using slice.