Copying objects bytearray vs for in loop



4 Comments

Share




I was curious, which of those would be quicker in the “copying objects” battle — bytearray / for in loop.
Foreseeing your possible thoughts, “yes” i do realize that those methods actually differ (bytearray copies the entire object, uses describeType etc), but still curiosity takes over :)
And, frankly, i was surprized with the results. See it for yourself.



// using ByteArray
function cloneObjectBA(value:Object):Object
{
var ba:ByteArray = new ByteArray();
ba.writeObject(value); ba.position = 0;
return ba.readObject() as Object;
}

// using for in loop
function cloneObjectForInLoop(value:Object):Object
{
var obj:Object = new Object();
for(var p:String in value) obj[p] = value[p];
return obj;
}

// >> Benchmark
var t:int, tb:int, tbAvg:int, tbTotal:int, tl:int, tlAvg:int, tlTotal:int;
var obj:Object = {};		// our testee ^_^
var numProps:int = 100000;	// num props to push to the object
var numCycles:int = 20;		// num cycles to run

// create properties
for(var i:int = 0; i < numProps; i++) obj["prop_"+i] = "val_"+i; trace("object", "->", numProps, "props");
trace("bytes", "\t|\t", "for in loop");
trace("-------------------------");

for(i = 0; i < numCycles; i++)
{
t = getTimer();
cloneObjectBA(obj);
tb = getTimer() - t;
tbTotal += tb;

t = getTimer();
cloneObjectForInLoop(obj);
tl = getTimer() - t;
tlTotal += tl;
trace(tb, "ms", "\t|\t", tl, "ms");
}
tbAvg = tbTotal/numCycles;
tlAvg = tlTotal/numCycles;

trace("-------------------------");
trace("AVG after "+numCycles+" cycles:");
trace("bytes", "\t|\t", "for in loop");
trace("-------------------------");
trace(tbAvg, "ms", "\t|\t", tlAvg, "ms");
trace("-------------------------");

My results on core2duo 3Ghz, win 10.2.152.26 debug:

object -> 100000 props
bytes | for in loop
-------------------------
678 ms | 32 ms
407 ms | 32 ms
380 ms | 32 ms
383 ms | 32 ms
384 ms | 31 ms
392 ms | 34 ms
405 ms | 32 ms
391 ms | 32 ms
393 ms | 32 ms
397 ms | 31 ms
390 ms | 31 ms
394 ms | 31 ms
395 ms | 31 ms
395 ms | 32 ms
399 ms | 31 ms
412 ms | 32 ms
390 ms | 31 ms
390 ms | 31 ms
389 ms | 32 ms
392 ms | 32 ms
-------------------------
AVG after 20 cycles:
bytes | for in loop
-------------------------
407 ms | 31 ms
-------------------------

K.O. for in loop wins :D

4 Comments (+add yours?)

  1. Reda Makhchan
    Mar 05, 2011 @ 02:10:59

    thks for the information ;)

  2. jloa
    Mar 05, 2011 @ 12:50:21

    u r welcome :)

  3. czubak
    Jul 02, 2012 @ 05:48:29

    great info, thanks

Leave a Reply

Spam protection by WP Captcha-Free