xdl
xdl

Reputation: 1110

flash as3 define variables before or in class constructor?

what is the difference between something like

package {
    public class Myclass {
        var txt:TextField = new Textfield();

        function Myclass() {

        }

    }

}

and

package {

    public class Myclass {

        var txt:TextField;

        function MyClass() {

            txt = new TextField;
        }
    }
}

I know that when you set create a new object, the class constructor is run, like this:

var object:Myclass = new Myclass();

In the 2nd way, this creates the new TextField.

My confusion is that in the 1st way, when is the TextField being created? Will it set aside memory for TextField if I import the class into another class? What if it was a static variable instead?

Upvotes: 1

Views: 1238

Answers (1)

span
span

Reputation: 5624

Memory will not be allocated until you instantiate so in that regard it doesn't really matter.

If you use a static variable that variable will take up memory since that is not bound to an instantiated object but rather it is like a global variable in that class.

EDIT: Great clarifiation from pkyeck on how to best construct and initialize an object in the comments: in AS3 code inside the constructor is supposed to be slow - so it's best to create an init() method and do the instanciation there and just all the init() inside the constructor. Code inside the constructor is not optimized by the Just-in-time compiler (JIT). To use JIT optimized code there is the possibility to call a function out of the constructor. The code inside that function is then optimized again. taken from here: je2050.joa-ebert.com/files/misc/as3opt.pdf – pkyeck

Upvotes: 6

Related Questions