I’ve heard from several sources that code in a constructor executes slower than code outside a constructor. So I decided to do a test. How much slower are constructors?

The methodology for the test is to run some expensive code in a constructor function and the same expensive code in a non-constructor function. This code is duplicated and not factored out to ensure that the the constructor function is doing the work directly rather than indirectly via a function call. Normally, you should factor this out, but here it would defeat the purpose of the test.

The work I’ve chosen to do is a big loop full of addition. The result of the computation is pointless, but stored in a public variable just to make sure that the compiler will not optimize out the loop, even though it probably wouldn’t anyhow.

Without further ado, here is the test app:

package
{
	import flash.text.*;
	import flash.events.*;
	import flash.display.*;
 
	public class ConstructorTest extends Sprite
	{
		private var __logger:TextField = new TextField();
 
		public function ConstructorTest()
		{
			__logger.autoSize = TextFieldAutoSize.LEFT;
			addChild(__logger);
 
			// Do the next frame so we don't test code in functions called FROM
			// a constructor, just in case.
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
 
		private function onEnterFrame(ev:Event): void
		{
			// We just wanted to do the test once
			removeEventListener(Event.ENTER_FRAME, onEnterFrame);
 
			// Constructor test
			var tester:Tester = new Tester(log);
 
			// Non-constructor test
			tester.init(log);
		}
 
		private function log(msg:*): void
		{
			__logger.appendText(msg + "\n");
		}
	}
}
import flash.utils.*;
class Tester
{
	public var total:int;
	public function Tester(log:Function)
	{
		var total:int = 0;
		var beforeTime:int = getTimer();
		for (var i:int; i < 50000; ++i)
		{
	  		for (var j:int = 0; j < i; ++j)
			{
				total += j;
			}
		}
		log("constructor time: " + (getTimer()-beforeTime));
		this.total = total;
	}
	public function init(log:Function): void
	{
		var total:int = 0;
		var beforeTime:int = getTimer();
		for (var i:int; i < 50000; ++i)
		{
			for (var j:int = 0; j < i; ++j)
			{
				total += j;
			}
		}
		log("init() time: " + (getTimer()-beforeTime));
		this.total = total;
	}
}

The output I get on a 2.2Ghz Intel Core 2 Duo with 2GB of RAM on Mac OS X 10.6 (Snow Leopard) is:

constructor time: 3446
init() time: 3437

The results I get on a 3.0Ghz Intel Core 2 Duo with 2GB of RAM on Windows XP SP3 are:

constructor time: 2518
init() time: 2519

These results seem to match, except for overall scale. While the init() function can sometimes be a tiny bit faster than the constructor, it is indeed a tiny bit. Unless you are doing almost all of your time-critical work in constructors, I don’t think you have anything to worry about.