Flash AS3 optimization - Fastest way to copy an array

Been having an interesting discussion on the papervision3d channel on freenode. (irc.freenode.net #papervision3d) The question asked by a member was: “What’s the fastest way to copy an array in flash as3?” So Tom Richardson and I made some tests for fun and profit (some guys bet a beer and pizza to Tom that a simple for() loop would win the race) so I started to make a small and barebones test. Obviously knowing we were getting the goods ; we set out to prove them wrong!

We were evaluating some small snippets of code:
- The basic for loop with push calls
- The basic while loop
- ByteArray copying/cloning
- Optimized for loop
- slice()
- concat()

We took an array of 500000 elements (all random floats) as source and went for a copy, and here are the results!

List of 500000 elements.
for() unoptimized: 118ms
for() key-key optimized: 30ms
while() key-key optimized: 30ms
Bytearray copy: 176ms
Array slice(): 19ms
Array concat(): 8ms

The obvious big time winner seems to be using concat()! Less function calls, less evaluations (and hey less code!) Extremely elegant as well :) Billy owes us pizza and beer.

Interestingly though, I was most surprised by the slowness of the unoptimized for() loop, scoring just over 100ms, compared to 180ms to perform a complete deep copy (bytearray)…that’s pretty poor. I guess developers would really gain some outstanding performance simply by optimizing their for() loops.

Using concat() also wins over slice() by about 10ms, which I’m not entirely sure why. I guess there might be addition function calls inside the language. Anybody got some insights on this?

Here is a small snippet demonstrating it and especially proving the copy array isn’t a reference:

Here is the source of the tests! Please don’t be afraid to kick and whine if something is not right. I’m also very interested in seeing if there would be an even FASTER way!

16 Responses to “Flash AS3 optimization - Fastest way to copy an array”

  1. rmd Says:

    It’d be interesting to see performance tests for copying a multidimensional array - recursive loops vs bytearray copy.

  2. Some ActionScript 3.0 Optimizations | Rozengain.com - New Media Development Blog Says:

    [...] Flash AS3 optimization - Fastest way to copy an array [...]

  3. Visual Harmonics » Post Topic » Copying arrays, need speed? Says:

    [...] http://agit8.turbulent.ca/bwp/2008/08/04/flash-as3-optimization-fastest-way-to-copy-an-array/ [...]

  4. Rendimiento y Optimización de AS3 | ¿y por qué no? Says:

    [...] La manera más rápida de copiar un array http://agit8.turbulent.ca/bwp/2008/08/04/flash-as3-optimization-fastest-way-to-copy-an-array/ [...]

  5. Actionscript Artist » AS3 Optimization - Fastest Way to Copy an Array Says:

    [...] information about this and the source code that he used to find this out can be found here. RSS Filed under: AS3 Flash Shortcut Keys [...]

  6. massimo_plustic Says:

    There is a much faster way to loop:
    Dont declare the counter var in the loop conditions.
    Its about 50% faster.

    //TEST-2b Barebones for loop, optimized

    var t2sb:Number = getTimer();
    var copy2b:Array = [];
    var l2b:int = list.length;
    var mb:int;
    for(mb = 0; mb < l2b; mb++)
    {
    copy2[mb] = list[mb];
    }
    var t2eb:Number = getTimer();
    trace(”for() key-key optimized b: “+(t2eb-t2sb)+”ms”);

  7. Benoit Beausejour Says:

    I disagree. According to my tests, declaring the loop counter in the condition doesn’t affect the outcome. I added a 7th test to the list that doesn’t declare the loop counter in the condition and the time output between test 2 and test 7 were almost always very close to the same (varying from 1 to 2 ms each)

    List of 500000 elements.
    1. for() unoptimized: 144ms
    2. for() key-key optimized: 35ms
    3. while() key-key optimized: 35ms
    4. Bytearray copy: 205ms
    5. Array slice(): 24ms
    6. Array concat(): 10ms
    7. for() key-key optimized again: 36ms

    You can repeat this test many tests and sometimes test 2 is faster by 1-2 ms, sometimes test 7 is faster by 1-2 ms. Overall, this proves to me that declaring the loop counter in the condition or outside has absolutely no effect on the performance of the loop.

    You can download the updated test file here and see for yourself:
    http://agit8.turbulent.ca/source/array_copy_speed.fla

  8. Eric Poirier Says:

    Well I’m with Benoit on this one, from what I can see declaring the loop counter inside or outside seems to bring a neglectable perf difference.

  9. AS3-Fastest way to copy an Array 数组复制的效率 | Why? Nowhy! DFdou's Blog Says:

    [...] information and the source code can be found here:Flash AS3 optimization - Fastest way to copy an array [...]

  10. joesteele Says:

    In the concat() case - what happens if you try to modify the array after copying? I wonder if it is really copying the data or just pointing to the other Array.

  11. Benoit Beausejour Says:

    Hi joe, it’s copy not a pointer :) That’s the whole point!
    So if you modify the copy, it’s not modifying the original :)
    -b

  12. joesteele Says:

    that is my question — if underneath they are really just sticking the original array on the end *until* you modify it. It’s called “copy-on-write” and it’s a pretty common technique to speed things up.

  13. joesteele Says:

    In that case — you would see a lag the first time you try to modify the new;y concat’d Array. If you don’t see a lag - that means that a true copy was made.

  14. Várias técnicas de melhores práticas e otimização em ActionScript 3.0 e Flex. « José Carlos Fiel Says:

    [...] Fastest way to copy an array http://agit8.turbulent.ca/bwp/2008/08/04/flash-as3-optimization-fastest-way-to-copy-an-array/ [...]

  15. Várias técnicas de melhores práticas e otimização em ActionScript 3.0 e Flex. « José Carlos Fiel Says:

    [...] Fastest way to copy an array http://agit8.turbulent.ca/bwp/2008/08/04/flash-as3-optimization-fastest-way-to-copy-an-array/ [...]

  16. ActionScript 3.0 Benchmark | Flash-Square Says:

    [...] Fastest way to copy an array http://agit8.turbulent.ca/bwp/2008/08/04/flash-as3-optimization-fastest-way-to-copy-an-array/ [...]

Leave a Reply


capsule omeprazole cialis rx buy ultram free levitra samples treatment for herpes buy cialis cheap loss of hair buy body building supplement pharmacy lipitor buy cialis on line augmentin doses new levitra ultram information healthy immune system allergic benadryl synthroid tablets antibiotics and dogs purchase cialis online without prescription how to treat flu xanax interactions with other medicines claritin pill hoodia order buy cialis without prescription ranitidine pregnancy cialis online without prescription herpes cures that work augmentin doses cheapest generic cialis online online stores hair loss products levitra without prescription vitamin c buy cheap amoxil without prescription online pharmacy viagra buy cialis on line buy levitra approved cialis fda about cialis viagra order online cialis prescription buy phentermine nausea cure toprol 50mg antibiotic chlamydia cialis levitra viagra menopause gum buy cialis online now buy buspar prednisone 10mg dogs weight buy cheap cialis dogs antidepressants buy cheap tadalafil uk cialis without rx clomid buy viagra online australia famotidine 20mg stomach parasites free samples viagra high blood calcium levels effexor dose hyaluronic acid buy buy cialis online serevent generic ibuprofen withdrawal otc claritin cialis and purchase coumadin side effects total health solutions buy tramadol cheap fertility in women purchase cialis online without prescription cialis without a prescription buy bone maker strontium cheap alcoholism treatment risperdal anxiety buy buspar can i get a viagra today levitra effect augmentin doses prozac antidepressants ways to make your penis bigger buy phentermine without prescription drug zithromax buyviagra cialis how do you treat lung cancer purchase meds without prescription how to purchase cialis drugs for diabetes valium and alcohol generic viagra on line how to white teeth motilium buy alternative treatment arthritis levitra cialis viagra cheap impotence drug generic cialis delivery phentermine by fedex sale levitra cialis prescription online order on line medicine without prescriptions abscess infection cats buy celexa how buy viagra lasix side effects chronic heart failure cheap msm buy lasuna cheap viagra order online promethazine tablets how to get viagra purchase levitra online pain meds without prescriptions stop hair loss buspar online viagra experience increase your erection clonazepam overdose xanax dosages order phentermine alavert drug how to cure acne viagra online usa cialis canadian pharmacy buy precose cialas on line buy amiodarone drug contraception pill levitra overnight buy zovirax finasteride prescription claritin 10mg levitra cheap online viagra for sex all natural antibiotics pain in left side home treatment for edema glucophage cialis canada pharmacy buy cialis online vpxl herbal levitra without prescription levitra online online prescription for cialis rx-viagra cat skin disorders how to treat prostate cancer yeast diflucan what does viagra do to females zyban how to use cialis advice viagra online without prescription