PDA

View Full Version : Class instantiation inside class



RubenFlash
December 24th, 2009, 06:46 AM
Performance wise, is it better to instantiate inside or outside the constructor?



public class example {
private var _mc:MovieClip = new Movieclip();
function example(){
}
}




public class example {
private var _mc:MovieClip;
function example(){
_mc = new Movieclip();
}
}

_kp
December 24th, 2009, 07:44 AM
I don't think there much of a difference in performance.

I use clearer way, that is never declaring class variables other than statics and only initialize a variable when needed. I think it looks messy otherwise when some variables are declared and others are not. In many cases it's decided in the constructor anyway what values most variables get.

Krilnon
December 24th, 2009, 01:15 PM
Neither, I think, because both of those code regions are interpreted rather than JIT compiled (and then executed). At least, that's the way Flash Player was reported to work at some point and I haven't heard of any change since then. That's one reason that you see people have constructors that simply call an init function. That function will have been compiled by Nanojit, so theoretically it has a much larger chance of running faster.

However, if you're solely calling the constructor for MovieClip, then it probably won't make too much of a difference, because most of the MovieClip constructor is going to be (native) compiled C++ anyway.

RubenFlash
December 24th, 2009, 01:53 PM
I'm asking because I read that in the class constructor memory leaks can't happen. Actually it was here in the forum that I read that:

http://www.kirupa.com/forum/showpost.php?p=2138997&postcount=27

But from what you guys are saying, in terms of performance, there's no noticeable impact. Thanks!

Krilnon
December 24th, 2009, 02:09 PM
That post isn't correct in its blanket statement that constructors can't cause memory leaks.