Initialize inline – debug longtime
Today I finally solved a memory leak issue in one of our projects after hunting it down line by line. And as in most cases the problem was in a few miserable lines of code. This time however, the problem was not that obvious after I had found it.
When writing classes one may initialize properties inline – give them a default value when the class is instantiated without having to do anything in the constructor:
class InlineTest{
private var inlineInit:Number = 20;
…
}
I’ve found this quiet a handy alternative to initializing all properties in the constructor, especially when I have lots of properties. However, as I was painfully tought by a hard late night debugging session you should not us inline initialization for reference data types (objects).
Consider this class:
class InlineTest {
public var arr:Array = new Array();
public function InlineTest(init:String) {
arr.push(init);
}
}
I would have imagined that the arr-property is initialized as an empty array for each instance of the class. However, Flash initializes inline properties only once (when the class is defined). When the instance is created all properties of the class are copied to the instance’s scope. Primitive data types work without a problem because the actual value of the property is copied. In the given example when the arr-property of the type Array is copied, the instance receives the pointer to the actual array, so that it actually behaves like a static property.
Trying the following:
var a:InlineTest = new InlineTest("Something");
var b:InlineTest = new InlineTest("Something else");
trace(a.arr.length);
Will actually trace "2". Go easy on those inline initializations…





