Tip #8 in my Top 10 Performance Tips For 2012 was to reduce static accesses of variables, functions, etc. in favor of non-static variables and, especially, local variables. I neglected to reference one of my articles and it was pointed out to me that I hadn’t actually written such an article! So today I’ll elaborate on my tip and show why you should prefer non-static and local variables so you can find out just why it deserves its place as a top tip.

To test my claim that static is significantly slower than non-static and local variables, let’s look at a simple test app:

package
{
	import flash.display.*;
	import flash.text.*;
	import flash.utils.*;
 
	public class StaticTest extends Sprite
	{
		private var tf:TextField = new TextField();
		private var nonStatic:Number = 0;
 
		private function row(...c): void { tf.appendText(c.join(",")+"\n"); }
 
		public function StaticTest()
		{
			tf.autoSize = TextFieldAutoSize.LEFT;
			addChild(tf);
 
			var REPS:int = 100000000;
			var i:int;
			var temp:Number;
			var local:Number = 0;
			var beforeTime:int;
 
			row("Variable", "Time");
 
			beforeTime = getTimer();
			for (i = 0; i < REPS; ++i)
			{
				temp = Math.PI;
			}
			row("Static", (getTimer() - beforeTime));
 
			beforeTime = getTimer();
			for (i = 0; i < REPS; ++i)
			{
				temp = this.nonStatic;
			}
			row("Non-Static", (getTimer() - beforeTime));
 
			beforeTime = getTimer();
			for (i = 0; i < REPS; ++i)
			{
				temp = local;
			}
			row("Local", (getTimer() - beforeTime));
		}
	}
}

I ran this test with the following environment:

  • Flex SDK (MXMLC) 4.5.1.21328, compiling in release mode (no debugging or verbose stack traces)
  • Release version of Flash Player 11.1.102.55
  • 2.4 Ghz Intel Core i5
  • Mac OS X 10.7.2

And got these results:

Variable Time
Static 760
Non-Static 214
Local 198

Static vs. Non-Static Performance Test Chart

As you can see, the non-static and local variables far outperform the static variables. If you’re going to be doing a lot of variable access, you should definitely consider caching that variable as a non-static field or local variable.

Spot a bug? Have a tip? Post a comment!