Array Length Outside Loop
From ActionScript Performance Wiki
Contents |
Purpose
Test how much faster it is to store an array’s length in a variable outside of a loop.
Code
package { import flash.display.Sprite; /** * @author Nicolas Schudel */ public class Test extends Sprite { public var array:Array = []; public var n1:Number = 123456; public function Test() { var i:int = 10000; while (i--) array.push(1); trace(new PerformanceComparison(10000, inside, outside).start()); } private function inside():void { for (var i:int = 0;i < array.length;i++) { array[i] = 2; } } private function outside():void { var n:int = array.length; for (var i:int = 0;i < n;i++) { array[i] = 2; } } private function insideWithOutsidePerformance():void { //It's also possible to define it in the for-loop but in the first part where defining the iterator index //++i can potentially be faster than i++ for (var i:int = 0, n:int = array.length;i < n; ++i) { array[i] = 2; } } } }
Results
Compiler version: 3.3.0.485, Player version: MAC 10.0.2.54, Operating System: Mac OS 10.5.8
- Test 1
- time 19601 64% slower
- Test 2
- time 11985
Compiler version: 3.3.04852, Player version: WIN 10.0.45.2, Operating System: Windows XP
- Test 1
- 14993 ms, 64% slower
- Test 2
- 9127 ms, best
Conclusion
A big performance gain for long arrays and long loops.

