Hey hey, someone recently asked: the fastest way to copy an array. Today I will tell you three methods based on the speed: you may already know
Hey, someone recently asked: the fastest way to copy an array. Today I will tell you three methods based on the speed: you may already know!
1. slice ();
(Function (){
Var abc = ["abc", "cad"];
Var cab;
Cab = abc. slice ();
Abc [0] = "ccc ";
Alert (cab );
Alert (abc );
})();
Because slice is a built-in method, it is the fastest.
2. concat ();
(Function (){
Var abc = ["abc", "cad"];
Var cab;
Cab = []. concat (abc );
Abc [0] = "ccc ";
Alert (cab );
Alert (abc );
})();
3. for... in
(Function (){
Var abc = ["abc", "cad"];
Var cab = [];
For (var k in abc ){
Cab [k] = abc [k];
}
Abc [0] = "ccc ";
Alert (cab );
Alert (abc );
})();
2 Responses to "three methods for copying arrays"
- Jade said: September 22, 2011
Var s = + new Date; var a = ['1', '2', '3']; var len =. length; for (I = 0; I <10000; I ++) var B =. splice (0, len); e = + new Date; alert (e-s); // 32 is indeed the fastest
Three other methods:
Var s = + new Date; var a = ['1', '2', '3']; for (I = 0; I <10000; I ++) var B =. join (','). split (','); e = + new Date; alert (e-s); // around 45, slightly slower
Var s = + new Date; var a = ['1', '2', '3']; for (I = 0; I <10000; I ++) var B = JSON. parse (JSON. stringify (a); e = + new Date; alert (e-s); // 68 the parsing of this involved object is created
Var s = + new Date; var a = ['1', '2', '3']; var len =. length; for (I = 0; I <10000; I ++) var B =. splice (0, len); e = + new Date; alert (e-s); // 34 this method is similar to slice