Nested Functions, how are they garbage collected i

2019-07-27 07:53发布

问题:

I have a very complex function in as3. The function is composed of many other functions which are nested inside of it. The main function has variables and all it's nested functions also have their own variables. Some of the nested functions are called by events that were added in the main function or in another nested function.

Now I want to know, when will my main function be garbage collected? When will the code be out of the main function? And when will the variables and the events and the nested functions be garbage collected?

P.S.: To add some more detail. Imagine my main function is called loadImages() and that it contains a bunch of nested functions: connectToServer(), sortImages() and onImagesLoaded(). When loadImages() is first called, it will create a url variable and an images array variable. Then it will call it's inner function called connectToServer(). This function will connect to the server, start downloading the images and add an onComplete event listener that will call onImagesLoaded() when all images have been loaded. Once all images are loaded, because of the event, onImagesLoaded() is called. This function will remove the onComplete event listener and will call sortImages() and pass it the loaded images as a parameter. After that, sortImages() will sort the images alphabetically and put them in the images array of the main function loadImages(). Finally, loadImages() will addChild the images in the array to the stage.

Thank You.

回答1:

Nested functions will capture variables from the outer function and could preserve the life of those variables, possibly unexpectedly or unnecessarily. You should avoid using nested functions unless you specifically need the extra functionality they provide (capturing the outer variables).

There's also a performance penalty for using nested functions, but it really only shows up in useless micro-benchmarks that should never affect a real-world app.

If you need to use nested functions, then make sure you remove them as event listeners when you're done with them. Doing that will make them available for garbage collection. You can make sure you always register them as weak event listeners so the event will not be counted towards whether or not they (or the variables they captured) are available for GC. However, since they are nested functions it's very likely the only thing keeping them around is the event registration.