One of my co-workers at McKinney asked me a few days ago if the gains for using the new AS3 Vector class were worth the trouble. I linked them this article by Mike Chambers, where he does a really nice speed test of the Vector class versus the common array. I still wanted to try my own test just to see, and the results are actually very different from what I expected.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | package { import flash.display.Sprite; import flash.events.Event; import flash.utils.getTimer; import org.flashdevelop.utils.FlashConnect; public class Main extends Sprite { protected var _vectorTest:Vector.<int>; protected var _arrayTest:Array; protected static const TOTAL:int = 5000000; public function Main():void { if (stage) init(); else addEventListener(Event.ADDED_TO_STAGE, init); } private function init(e:Event = null):void { removeEventListener(Event.ADDED_TO_STAGE, init); _vectorTest = new Vector.<int>(TOTAL, true); _arrayTest = []; for (var k:int = 0; k < TOTAL; k++) { _vectorTest[k] = k; _arrayTest[k] = k; } for (var m:int = 0; m < 20; m++) { runVectorTests(); //runArrayTests(); } } protected function runVectorTests():void { var vectorStart:int = getTimer(); var count:int = _vectorTest.length; for (var m:int = 0; m < count; m++) { _vectorTest[m] = Math.random() * TOTAL; } var vectorFinish:int = getTimer() - vectorStart; FlashConnect.atrace(vectorFinish); } protected function runArrayTests():void { var arrayStart:int = getTimer(); var count:int = _arrayTest.length; for (var n:int = 0; n < count; n++) { _arrayTest[n] = Math.random() * TOTAL; } var arrayFinish:int = getTimer() - arrayStart; FlashConnect.atrace(arrayFinish); } } } |
As I expected, in all of my tests the Vector class beat the crap out of the array.
Vector: 450 ms average
Array: 753 ms average
What I was curious to see was if setting the length of the vector, and setting it to fixed would lead to another performance leap.
1 | _vectorTest = new Vector.<int>(); |
Plain Ole Vector: 455 ms average
1 | _vectorTest = new Vector.<int>(TOTAL); |
Vector w/ Length NOT Fixed: 454 ms average
1 | _vectorTest = new Vector.<int>(TOTAL, true); |
Vector w/ Length, Fixed: 452 ms average
These results are VERY disappointing! While the performance of the Vector is truly impressive, isn’t the point of fixing a Vector’s length for more speed? I don’t know if I can justify the effort for an average of 3 ms gain. Keep in mind this an average, the plain vector actually beat or tied the others sometimes.
Here’s a link to my FlashDevelop project if you want to try for yourself.
