upwithabang web designer resources
del.icio.us icon

Avoid Statics

Flash takes much longer to call a static method than a instance method. If you have a method that you frequently call, considering making it an instance member of its class. It will speed up performance.

Example (pseudo-code):

Main class that runs tests

package ProfileTests
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.getTimer;

	public class Main extends Sprite
	{
		private static const max:Number = 10000000;
		static public function TestStatic() : void	{ }
		public function TestMember() : void	{ }

		public function Main():void {
			addEventListener(Event.ENTER_FRAME, Go);
		}

		private function Go(e:Event) : void	{
			var start:Number;
			var end:Number;
			var i:Number;

			start = getTimer();
			for (i = 0; i < max; i++ ) TestMember();
			end = getTimer();
			trace("member method time: " + (end - start));

			start = getTimer();
			for (i = 0; i < max; i++ ) Main.TestStatic();
			end = getTimer();
			trace("local static method: " + (end - start));

			start = getTimer();
			for (i = 0; i < max; i++ ) StaticTester.DoNothing();
			end = getTimer();
			trace("external static method: " + (end - start) + " *******");

			var st:StaticTester = new StaticTester();
			start = getTimer();
			for (i = 0; i < max; i++ ) st.DoNothingMember();
			end = getTimer();
			trace("external member method: " + (end - start));

			removeEventListener(Event.ENTER_FRAME, Go);
		}
	}
}

External static class

package ProfileTests {
	public class StaticTester{
		public function DoNothingMember() : void {}
		public static function DoNothing() : void {	}
		public function StaticTester() { }
	}
}
		

Sample run times

Notice external statics are about 30% slower

member method time: 1907
local static method: 1933
external static method: 2531 *******
external member method: 1934

member method time: 1952
local static method: 1921
external static method: 2565 *******
external member method: 1971

member method time: 1960
local static method: 1933
external static method: 2546 *******
external member method: 1896
Did you find this article userful for your website?
If so, why not provide a link to it? Just copy the following to your web page:
      <a href='http://upwithabang.com/articles/flash-optimizing.html'>
Actionscript Optimizations
</a>

Share this:  del.icio.us icon