Is there a performance hit when iterating over object attributes vs. iterating an array?
Example, using objects:
var x:Object = {one: 1, two: 2, three: 3}; for (var s:String in x) { trace(x[s]); }
Vs using an array
var a:Array = [1, 2, 3]; var len:Number = a.length; for (var i:Number = 0; i < len; ++i) { trace(a[i]); }
So – which is faster and most importantly by what factor?
IIRC, in some JavaScript implementation iterating over objects attributes is slower up to 20x but I haven’t been able to find such measurement for ActionScript2.
I just tried a very similar test, but iterating just once over 200k elements, with opposite results:
I suspect Luke’s test is dominated by loop overhead, which seems bigger in the array case. Also, note that the array took significantly longer to populate in the first place, so ymmv if your task is insert-heavy.
Also, in my test, storing arr.length in a local variable gave a measurable performance increase of about 15%.
Update:
By popular demand, I am posting the code I used.