Posts Tagged ‘slice

12
Mar
09

Fastest Way to Copy An Array: Concat() or Slice(0)

What is the fastest way to copy an array? Concat or Slice? There is only one way to find out. FIGHT!

OK, so we can dismiss any kind of for-loop – far too slow, so that leaves us with:
1) array.concat() – i.e. concatenate an array onto nothing and deliver that as a new array.
2) array.slice(0) – i.e. return a new array consisting of all of the elements of the old array – from 0 till the end (up to a max of 16777215)

I’ve set up an array with a cool 1million entries (ok, it is not big, and it is not clever so it certainly isn’t cool). I need to copy this. The following code executes each method once on every iteration. It keeps a running total and records the average time each takes. I’ve limited the code to 100 iterations.

import flash.utils.*;

var iteration_count:int=0
var concat_total:int=0
var slice_total:int=0

//Set up array to copy
var test_array:Array = [];
for(var i:int = 0; i < 1000000; i++) test_array.push(i);

addEventListener(Event.ENTER_FRAME,iterate)

function iterate(e:Event=null):void
{
concat_total+=testConcat()
slice_total+=testSlice()
iteration_count++
trace(“Av. concat time=”+(concat_total/iteration_count)+” Av. slice time=”+(slice_total/iteration_count))
if(iteration_count>99) removeEventListener(Event.ENTER_FRAME,iterate)
}

//test array slice
function testSlice():int
{
var time_slice_start:Number = getTimer();
var slice_copy:Array = test_array.slice(0);
var time_slice_end:Number = getTimer();
return time_slice_end-time_slice_start
}

//test array concat
function testConcat():int
{
var time_concat_start:Number = getTimer();
var concat_copy:Array = test_array.concat();
var time_concat_end:Number = getTimer();
return time_concat_end-time_concat_start
}

On my laptop I’m clocking the concat at 14ms and the slice at over 29ms.

So a conclusive result. concat is twice the speed (with large arrays – the difference diminishes considerably with smaller arrays)

Thinking about it the may be some issues with memory usage and garbage collection that could affect the test.
Give the code a few run throughs and see what you get. Let me know if your results are markedly different.




Categories

Flash on the Beach 2010

Flash on the Beach 2009

Swingpants at FOTB2009

Twitter Updates