Garbage Collection
SoundHolder.playSound(Object(root).meterAlert,0,0, new SoundTransform(.1));does 'new SoundTransform()' automatically get garbage collected since I'm not pointing anything to it or does it stay in memory
KirupaForum > Flash > ActionScript 3.0
Posted on: 11-21-2008, 01:34 PM
View Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
Garbage Collection
This is a rather general question. I'm curious to garbage collection in ActionScript. I suppose garbage collection *is* implemented in the Flash Player, but I wonder how it works.
My guess is that 'delete' more or less immediately invokes the gc, and that every now and then, the gc skims allother non-referenced objects.
Does anyone have any more knowledge about this, or could someone refer me to another source?
Garbage Collection
I'm involved in a project where designers just create objects on the stage. They don't use any actionscript, i.e., all objects are being created directly by dragging them from the library and dropping them onto the stage.
I know that the garbage collector removes all objects that are unreferenced, but what happens when there is no code involved? Does the garbage collector remove the objects if they are not present at a given frame?
Is there any way to optimize garbage collection without any actionscript involved?
Garbage Collection
If this is all the code I have in an fla, is box1 eligible for garbage collection? The function creates a new sprite, removes it, then sets the variable to null. Is setting it to null and removing it from the display list all I need to do for the garbage collector to get rid of it? I am aware that you have to deal with event listeners in regards to this, but I don't have any with this code.
ActionScript Code:
function myFunction():void
{
var box1:Sprite=new Sprite();
box1.name="box1";
addChild(box1);
removeChild(getChildByName("box1"));
box1=null;
}
Garbage Collection
Hi!
I have encountered a strange behavior of the garbage collector: It seems that he's not removing some classes (Sprite, String...) although there is no reference to them whereas other classes are collected (Object, BitmapData, Array). I've used a Dictionary with weak keys to check if objects are removed. Please see the example code below. What's going on here?
Thanks for your help,
Andreas
Attach Code
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.TimerEvent;
import flash.text.TextField;
import flash.utils.Dictionary;
import flash.utils.Timer;
public class Main extends Sprite
{
private var d:Dictionary;
private var c:int = 0;
private var textField:TextField = new TextField();
private function printDict(event:TimerEvent=null):void
{
textField.text = "Step " + c + "
";
for ( var item:* in d )
{
textField.text = textField.text + "key:" + item + "
value: " + d[item];
}
c++;
}
public function Main():void
{
addChild(textField);
// Create dictionary with weak references.
d = new Dictionary(true);
// *** These objects are removed from the dictionary *** //
//var object:Object = new Object();
//var object:TimerEvent = new TimerEvent(TimerEvent.TIMER);
//var object:BitmapData = new BitmapData(100, 100);
var object:Array = [100, 200, 300];
// *** These objects are not removed from the dictionary *** //
//var object:Object = "A String";
//var object:Object = new int(1);
//var object:Object = new Sprite();
//var object:Shape = new Shape();
//var object:TextField = new TextField();
d[object] = 1;
printDict();
object = null;
var t:Timer = new Timer(1000, 20);
t.addEventListener("timer", printDict);
t.start();
}
}// END OF CLASS
}
Garbage Collection
Ok, so after using the Profiler perspective in flex, I've been scared to death of memory leaks. Top on my list of things to do is to find a fix. I have an idea that could work, but definitely needs a better approach. If anyone knows of some rare, help methods that could turn this into something, please let me know.
So I just found out about the flash.utils.describeType function that retrieves a list of everything about an object. I use it to find all the variables I'll be nulling when I want to erase an object for garbage collection. I have a function "destroy" that will run a loop that sets all of the non-number variables to null before removing the child. Now, is there a function that I could use instead of running a loop?--it's a bit CPU intensive. also, because I'm using something like Child["variable"] = null; to nullify a property, it won't work with private variables. the thing is, the memory is next to nothing whenever I have the destroy function working whenever I want to get rid of something, but I can tell there's a bit of lagging.
anything will help. thanks.
(i'm sure senocular will quickly refer me to one of his posts I've overlooked )
Garbage Collection
Yo all.
Has anybody any idea on how to make the supposed flash MX garbage collection mechanism to work?
Cheers
RemoveMovieClip And Garbage Collection
Hi,
I'm making a game in flash lite 2, but since my problem applies to general flash programming, I'm posting it here.
I have a class (GameController) that attaches a movieclip, which is extended by my Game class. Whenever you die, go to a new level, etc, I delete this movieclip with removeMovieClip, and attach it again. After a few times, the flash lite player runs out of memory. This problem wouldn't be noticeable on a normal flash game because you would have a lot more memory available, but off course a cellphone only has limited memory.
The reason this problem is happening is obvious - the garbage collection hasn't done it's job before I attach the game again. But I have no idea how to solve this. Should I use delete on every single variable in my Game class? Would this even make any difference, as it would probably only flag the variables for deletion, which I assume removeMovieClip also does, but I'm not sure.
Any ideas? Thanks!
Is It Possible To Force Garbage Collection (F8)
I'm running a desktop app (projector), and I was wondering if there is any way to explicitly call for garbage collection. I don't think there is, but I thought someone may have figured out a way to do so.
I know that the garbage collection flags deleted objects and variables for deletion at a later time, but it seems terribly inefficient when there are many things to delete or clean up while moving from screen to screen.
I'm attaching and removing a lot of movie clips on different screens, and it seems like flash is just hogging memory up.
I know minimizing the app and restoring it causes the garbage collector to deallocate memory, but is there another way ?
Or is there a more efficient way to attach and remove clips than just using attachMovie() and removeMovieClip().
Any input is appreciated, thanks for your time.
Question About Garbage Collection
If I create an empty movieClip container and add objects to it and then use removeChild on the MovieClip (not it's child elements) then does it put the movie AND all of the child elements into the garbage collection?
I have so many little unique objects being added and it'd be easier to do it that way if it worked.
Problem With Garbage Collection (I Think)
howdy all. i'm having a problem removing dynamically created objects. at least i think i am, as the movie is slowing down considerably after a number of objects are added and (supposedly) deleted. here's what i'm doing:
in the onClick handler:
Code:
if (particles.length >= maxParticles) {
for (var i:int=particles.length-1; i>=0; i--) {
removeChildAt(i);
delete particles[i];
}
particles = new Array();
}
for (var i:int=0; i<maxParticles; i++) {
particles.push(new Particle(new Point(event.stageX, event.stageY), new Point(stage.stageWidth*Math.round(Math.random()), stage.stageHeight*Math.random())));
addChild(particles[i]);
}
where a Particle is created from the Particle class and the particles array is just keeping track of each particle added. basically on a mouse click, a certain number of particles are created and added to the stage. on the next mouse click, the previous particles are removed and new ones are added. by the sixth or seventh mouse click, the slowdown is terrible, leading me to believe that the particles are still "out there", just not visible on the stage. i tried following examples from Essential Actionscript and Senocular.com's tutorial, but i'm having no luck.
any assistance would be HUGELY appreciated. thanks!
Improving Garbage Collection
I have a game which, once everything is loaded and generated, takes up 150 mb in ram. Being relatively new to AS3 I found out (after many hours of debugging!) that one has to remove all references to the game once it has been removed from the stage to make it available for garbage collection. Ok, no problem, many other languages have the same issues.
The problem is I can close and load the game many times before Flash decides to clear the ram, and often my Flash application ends up taking more than 1 gb before Flash decides now is the time...
Is there really no way to force flash to delete the loaded game?
TIA
Tweens And Garbage Collection
I'm creating a website with lots of sub-navigation items, for example extensive portfolio with thumbnail galleries, long lists of services that are expandable, etc... most of the click, mouse over and mouse out events have tweens associated with them. I've read a lot of posts on here about people having trouble with tweens getting 'stuck,' and I'm having the same problem too... I am defining the Tween outside of the function, and creating a new Tween every time I call one, but still am getting the occasional tween to just stop halfway through it's intended progress...
Is there something I'm not understanding about garbage collection or re-using tweens? here's an example of some code that I pulled out of a class, I have a few different isntances of similar types of tweens. At one point there are about 20 tweens occuring at the same time as the portfolio navigation appears, and there are 32 menu items.
ActionScript Code:
var fadeTween:Tween;
var tickTock:Timer = new Timer(500,5)
tickTock.addEventListener(TimerEvent.TIMER, beginTweens);
tickTock.start();
var k:int = new int();
function beginTweens(Event:TimerEvent):void
{
k += 1
fadeTween = new Tween(getChildByName("n" + k.toString()),"y",None.easeOut,250 + (k * 20),(k * 20),.75,true)
fadeTween = new Tween(getChildByName("n" + k.toString()),"alpha",None.easeIn,0,1,1.25,true)
}
this moves instances of a class I created, which are named "n1" "n2" "n3" "n4" and "n5" and is called after some items have loaded, and is also occuring while a seperate class is tweening in some images to be displayed... every time when I preview it the first time child "n1" gets stuck approximately 100 pixels, or a half second, away from it's final destination. Help!
Garbage Collection Detection
guys,
is there a good tutorial to detect how much memory consumption so that we can detect garbage collection well??
or any good reference other than GSkinner's work?? thanks!
Question About Garbage Collection
ActionScript Code:
//create land sprite
var land:Sprite = new Sprite();
land.name = "land";
addChild(land);
land.graphics.lineStyle(1, 0xFF0000, 1, false, "normal", "square", "miter", 3);
land.graphics.drawCircle(100,100,50);
(land)?trace("exists"):trace("doesn't exist"); //does it exist? Yes.
contains(land)?trace("does contain"):trace("doesn't contain"); //is it displayed? Yes.
removeChild(land); //remove it from display
land = null; //remove it from memory
var land:Sprite = new Sprite(); //recreate new land sprite
//but you can't because you get this compile error:
//1151: A conflict exists with definition land in namespace internal.
addChild(land);
(land)?trace("exists"):trace("doesn't exist");
contains(land)?trace("does contain"):trace("doesn't contain");
If land is completely gone after I removeChild() and set it = to null, I should be able to create a new land sprite using the same name, right? But I can't. The compile error I get is in a comment in the code above.
A Thought About Garbage Collection
hello;
to help yourself with GC, anytime you create something, add a comment that itemizes its footprint:
ActionScript Code:
var S : Sprite = new Sprite();
addChild( S );
// GC:
// - will need to remove from display list when finished with it
// - will need to null the reference to the sprite when finished with it
var my_object : my_custom_class = new my_custom_class();
// GC:
// - will need to send it a cleanup() when finished with it
// ... the cleanup() will handle any internal display list issues, internal evenlistener issues, internal class reference issues, etc
// - will need to null the reference to it when finished with it
addEventListener(Event.ENTER_FRAME , a_method , false , 0 , true );
// GC:
// - will need to removeEventListener when finished with it
A Garbage Collection Question
if I have a movieclip lets jsut call is MC1; now MC1 contains several different objects, and various objects it contains also have eventListeners and such, but all its children are only accesseible through it,
if I remove all the events assosiated with MC1 itself, and remove MC1 from the display list and set MC1 to null
the children of MC1 are not longer accesible accesible because MC1 is gone
.....will this make MC1 eligible for garbage collection?
I ask this mecause MC1 contains several different things and it would take a long time to set each one of eachs children to null, and remove the event listeners for all its children and grand children.
Thanks!
Garbage Collection Nightmare
i've been struggling with this stupid thing for hours
i have been reading articles and viewing examples of how to make things eligible for garbage collection. and i understand how that works... at least in theory.
from what I can tell, this SHOULD work,
Code:
var a:Object = new Object();
a.stupid = 'wow';
trace(a.stupid);
delete(a);
trace(a.stupid);
nope.. gives me this error
1189: Attempt to delete the fixed property a. Only dynamically defined properties can be deleted.
Maybe A Garbage Collection Problem...?
I have a simple actionscript3-controlled animation (specifically, using the Cubic.easeOut function). For some reason, the animations will randomly stop sometimes when I preview the movie. And it almost always happen when I run the debugger... I'm guessing this is a garbage collection problem?
I read up about how the process works... but my tween variables are stored in arrays that are referenced in the main class, so they shouldn't be garbage collected!!! Any clues?
Garbage Collection Question
I have a series of objects, each of which i've added to an array. In order to make them eligible for garbage collection I'm removing each object's listeners , removing the object from the display list, and then setting the object to null. Then I'm setting the array to null.
My question is: should i be removing each object from the array before i set the array to null? Even though the objects are deleted, does their reference in the array keep the garbage collector from picking them up?
Thanks!
Garbage Collection Clarity
I thought I understood this from other postings and Moock reading, but I find I'm still not entirely clear on what stuff I need to delete and what stuff is automagically deleted when I am done with an object. So, here some situations.
1) Suppose I have a CustomClass with private vars of the following types:
private var myNumber:Number;
private var myString:String;
private var myClip:MovieClip
private var myText:TextField
private var myArray:Array
private var myButton:Button
private var mySpecialClass:SpecialClass
a) suppose in the course of using an instance (myCCInstance) of that CustomClass I assign values to myNumber and myString, I assume when I delete myCCInstance the myNumber and myString will go away.
b) Now suppose for other types, I create new objects (i.e.
myText = someClip.createTextField(...);
myArray = new Array(1,2,3);
myClip = someClip.attachMovie(...);
mySpecialClass = new SpecialClass(...);
Will any of these be deleted when the myCCInstance is deleted or do ALL of them need to be deleted by some destroy method I write. If I need to delete stuff myself then.... to delete an array, I would assume myArray.delete will do the trick. To delete myClip, I assume I first need to use myClip.removeMovieClip and then the myClip variable will get deleted with the myCCInstance. To delete myText - I'm not sure what to do here. For mySpecialClass I must write a destroy method which dumps its appropriate stuff out and then I could have that method do a this.delete.
c) Suppose some of these refer to instances created at authortime on the stage-
myText = textOnStage_txt
myClip = clipOStage_mc
myButton = buttonOnStage_btn
I assume the items on stage will stay there, but the variables that reference these will be deleted automatically when myCCInstance is deleted.
Is all this correct?
Part 2 of my question is for the case of callback or nested functions like an xml loader. Here is some sample code I found on the web. When this is all done, is the xml object gone?
Sorry to be such a dim bulb about all this.
Attach Code
private var myArray:Array;
private function setUpXML():Void{
myArray = new Array();
var xml:XML = new XML();
xml.ignoreWhite = true;
var thisObj:CustomClass = this;
// load xml
xml.onLoad = function(){
thisObj.onLoadXML(xml);
}
loadXML(xml);
}
private function loadXML(xml:XML):Void{
xml.load("myXML.xml");
}
private function onLoadXML(xml:XML):Void{
var nodes:Array = xml.firstChild.childNodes;
for(var i=0;i<nodes.length;i++){
myArray.push((nodes[i].attributes.myattr));
}
}
Force Garbage Collection?
I'm currently checking memory usage of an script, but even afer deleting classes, the memory usage does not drop, and even keep icreasing as new instances are created (and then deleted). I believe thit is because even these instances being eligible for garbage collection this is not happening because there's no need to free memory for new instances... How often garbage collection happens? Is there a way to force garbage collecion usign AS3 so I can check if my code is really removing the instances?
Application Garbage Collection
I'd like my FMS Application to unloaded shortly after the last user has disconnected.
From what I've read the Application unload process occurs during Garbage Collection which is kicked off after a) all clients have disconnected and b) a default interval of 20 minutes has elapsed.
So far the only place I've been able to find to possibl change the Application Garbage Collection time is System.xml <ResourceLimits><AppliactoinGC>.
However, after changing this value to 1 and restarting FMS, it still does not unload the app when I would expect.
Is there something I'm missing?
-Thanks
FlashStreams
Garbage Collection Issue As3
Having real problems with garbage collection in as3
Currently working on a project that is using a main movie clip to load other movie clips dynamicly, using loadURL.these sub movieclips are rather heavy in size, and function as standalone modules.
Our problem is that when we removeChild of the sub clips it is still present in memory (which from what I have read is normal untill garbage collection cycle is fired) however it doesn't seem to ever get removed.
how can we safely load movieclips and remove all references to them to make them eligible for garbage collection? current approach we are using is to publicly state the loader the say new loader() in an attempt to recycle rather that to try to send for garbage collection
Tween And Garbage Collection
No matter what I do I cannot solve a tween AS3 Garbage Collection problem I am having that is wreaking havoc on my tween instances working correctly/consistently. Some Sprites never tween at all, some do but only part way. And it effects different ones almost each time.
I have read a fair amount recently on AS3 Garbage Collection and improperly referenced Tweens and other asynchronous instances getting picked up in mid process. I am experiencing the signature inconsistent behaviour that the I have read of.
I have tried using class level Static and non static properties to store references to my Tween instances so they will not be marked for GC. No luck. I have placed references to them in Class level Arrays, I have also used TweenMax's static to() Method that insures that it will shield it from GC and its alt. non Static constructor instantiation, with persist:true. I also implemented another custom package; GCSafeTween(), other users said it does as it should, but it's not working in my case.
To test the GC problem, I edited the two eventListerners() in the Adobes' fl.transitions.Tween so that their default weakReference property was false. Doing this made the Tween work correctly. But that's a terrible solution.
Here's my code.....
Garbage Collection Frustration
Hey guys,
I have a project which creates 9 gallery frames. Each frame is a simple square movieclip with an alpha of 0. When all 9 movieclips have been created, I am attempting to tween them in using TweenLite or the Flash tween engine.
The problem comes completely randomly, my tween function cycles through each of the 9 movieclips and fades it to 1... but occasionally when I run the movie, the first movieclip stays at 0! This happens completely randomly and after some research I believe it is a garbage collection issue? Can anyone suggest how I can fix it?
What Is The Garbage Collection In Actionscript 3.0?
Could someone help me to understand what garbage collection is?
Does it mean that any object needs to be deleted after its being used? If yes, how can this be done? I heve heard about using (Null) or something like that.
Thanks,
fs_tigre
Garbage Collection Of Bitmaps
Can I be certain that if an object using 100 megs of memory is nulled and its listeners removed, garbage collection will eventually delete that object, or does it depend on the amount of ram on the user's system? I want to check that the System.totalMemory is less than it was before nulling the object before I try to load a new object.
Garbage Collection And Children
I am having issues removing a loaded swf completely so that it is eligible for garbage collection. I have removed all it's listeners, removed it from the display list, and set all references to it to null, but it still doesn't seem to be getting removed. I'm wondering, do I need to also remove all its children and their listeners as well or when I remove it, should its children also be removed regardless of whether they have listeners added to them?
Garbage Collection Practices
I did a search and a bunch of people have had problems with memory which lead to discussion of Garbage Collection.
I was trying to figure out the right way to delete stuff, and find out what needs to be done to make sure it really is deleted.
I have things like:
array with:
- Display object-> display object->display object->bitmap;
- Display object-> display object->display object->bitmap;
- Display object-> display object->display object->bitmap;
etc
i basically want to delete everything in this array, have a blank array to start my new thingy.
if i write this:
Code:
arr = new Array();
will everything be deleted? Considering those are visible. Do i have to do sth like,
Code:
for (var i:uint=0;i<arr.length;i++){
container.removeChildAt(i);
}
and would that be enough?
Garbage Collection Quick Question
I make a new instance of a class and put it in an Array and addChild it. Then after it's served it's purpose it is removeChild and spliced from its Array. At this point will Actionscript 3 depose of it in its Garbage Collection system? Or do I need to do something further? Just making sure I don't have all these extra instances slowing up my game.
Thanks in Advance!
Tween And Garbage Collection Problem
No matter what I do I cannot solve a tween AS3 Garbage Collection problem I am having that is wreaking havoc on my tween instances working correctly/consistently. Some Sprites never tween at all, some do but only part way. And it effects different ones almost each time.
I have read a fair amount recently on AS3 Garbage Collection and improperly referenced Tweens and other asynchronous instances getting picked up in mid process. I am experiencing the signature inconsistent behaviour that the I have read of.
I have tried using class level Static and non static properties to store references to my Tween instances so they will not be marked for GC. No luck. I have placed references to them in Class level Arrays, I have also used TweenMax's static to() Method that insures that it will shield it from GC and its alt. non Static constructor instantiation, with persist:true. I also implemented another custom package; GCSafeTween(), other users said it does as it should, but it's not working in my case.
To test the GC problem, I edited the two eventListerners() in the Adobes' fl.transitions.Tween so that their default weakReference property was false. Doing this made the Tween work correctly. But that's a terrible solution.
Here's my code. Its kinda stripped down just to show the setup.
Thanks for helping me solve this one!
PHP Code:
package {
import DataModel;
import StackDisplay;
import flash.display.*;
import flash.events.*;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
public class Main extends MovieClip {
private var _dataModel:DataModel;
private var _stackDisplay:StackDisplay;
private var _visibleAsset:uint;
private var _timer:Timer;
private var _timerTweenOut:Tween;
private var _timerTweenIn:Tween;
public function Main () {
_dataModel = new DataModel();
_stackDisplay = new StackDisplay(_dataModel, this);
configureListeners ();
}
private function configureListeners ():void {
_stackDisplay.addEventListener (Event.COMPLETE, initTimer, false, 0, true);
}
private function initTimer (evt:Event) {
_timer = new Timer(1500);
_timer.addEventListener (TimerEvent.TIMER, timerNext, false, 0, true);
_timer.start ();
}
private function timerNext (evt:Event) {
_timerTweenOut = new Tween(_stackDisplay.assetArray[_visibleAsset], "alpha", Regular.easeOut, 1, 0, 7, false);
_visibleAsset++;
_timerTweenIn = new Tween(_stackDisplay.assetArray[_visibleAsset], "alpha", None.easeOut, 0, 1, 7, false);
}
}
}
Display Objects And Garbage Collection
Hey everyone, first time poster here. I recently decided to take up as3 and check out all the new features, and so far I'm quite impressed with the movement towards OOP .
I have a question regarding garbage collection for objects in the display list... currently I am working on a project that involves creating visual arrays of movie clips linked to a class (lets call it skillItem). This class has quite a few listeners for different parts of the movie clip. The way I accomplished this was by dynamically adding a child (container) and using a for loop to addChild(skillItem) to this container with the proper information.
Now for my question... In my project the user can select different options from a combo box. When the combo box changes, it deletes the container MovieClip via removeChild(container), and creates a new one with a new skillItem Array. It is my understanding that removing a child also removes all of the children on its display list as well, this works in my project as it should. I've read that the only way to let flash know its okay to GC is to also remove the listeners associated with a child. So I guess my question is does removing the container child (and thereby removing all the skillItem children) also delete the listeners associated with the skillItem children and allow flash to GC properly?
[advanced] FP7 Scoping/Garbage Collection Bug (?)
I have noticed for some time that some of my projects, exported from Studio 8 for FP7, work as intended in FP8, but not in the original FP7. Today I tracked down the problem.
ActionScript Code:
function test() {
var testObj:Object = new Object();
testObj.funcToExecute = function() {
// trace via javascript because of the browser test
getURL("javascript:alert('executing after pause!')");
}
setInterval(testObj, "funcToExecute", 3000);
}
test();
This code works in FP8 (funcToExecute is executed), but not in FP7 (the latest, FP7r61). Now, I think the reason for that is that testObj is garbage-collected as soon as the call to test() exits, the reference to it from the setInterval notwithstanding. I think so because
ActionScript Code:
var testObj:Object = new Object();
testObj.funcToExecute = function() {
getURL("javascript:alert('executing after pause!')");
}
setInterval(testObj, "funcToExecute", 3000);
in the first frame (note the absence of a function now) works fine in FP7 (of course, otherwise it would be pretty famous), and so does
ActionScript Code:
var testObj:Object;
function test() {
testObj = new Object();
testObj.funcToExecute = function() {
getURL("javascript:alert('executing after pause!')");
}
setInterval(testObj, "funcToExecute", 3000);
}
test();
(note that testObj is defined outside of the function scope). Am[az|us]ingly,
ActionScript Code:
function test() {
var testObj:Object = new Object();
testObj.funcToExecute = function() {
getURL("javascript:alert('executing after pause!')");
}
setInterval(testObj.funcToExecute, 3000);
}
test();
(note that setInterval is invoked differently) also works fine in FP7, which leads me to conjecture that function references are treated differently from Object references from the point of view of garbage collection. Perhaps this is a "feature" of FP7 with which I am yet to familiarize myself?
Garbage Collection And Primitive Types
Does anyone know how primitive types and references are stored in memory? References store a memory location to an object, and ints, numbers and so on simply store the value directly. If I create alot local variables in a function that are primitive types or just references, what happens to them at the end of the function? Are the variable and references themselves sent to the garbage collector, or are they popped off a stack when the function is done executing?
Garbage Collection On Export For ActionScript
Does anyone know if items marked "Export for ActionScript" in a loaded SWF will ever be garbage collected?
I know that they won't be GC'ed in the main SWF, but when that main shell loads an external SWF module that also has library items set to export, and then later unloads that SWF --- will the module "Export for ActionScript" items ever be picked up by the GC, or will they continue to exist in the shell forever? (And add duplicates if I load that module SWF module multiple times)
Thanks!
Tween And Garbage Collection Problem
No matter what I do I cannot solve a tween AS3 Garbage Collection problem I am having that is wreaking havoc on my tween instances working correctly/consistently. Some Sprites never tween at all, some do but only part way. And it effects different ones almost each time.
I have read a fair amount recently on AS3 Garbage Collection and improperly referenced Tweens and other asynchronous instances getting picked up in mid process. I am experiencing the signature inconsistent behaviour that the I have read .
The solution is to store a reference of that object
I have tried using class level Static and non static properties to store references to my Tween instances so they will not be marked for GC. No luck. I have placed references to them in Class level Arrays, I have also used TweenMax's static to() Method that insures that it will shield it from GC and its alt. non Static constructor instantiation, with persist:true. I also implemented another custom package; GCSafeTween(), other users said it does as it should, but it's not working in my case.
To test the GC problem, I edited the two eventListerners() in the Adobes' fl.transitions.Tween so that their default weakReference property was false. Doing this made the Tween work correctly. But that's a terrible solution.
Here's my code. Its kinda stripped down just to show the setup.
Thanks for helping me solve this one!
ActionScript Code:
package {
import DataModel;
import StackDisplay;
import flash.display.*;
import flash.events.*;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
public class Main extends MovieClip {
private var _dataModel:DataModel;
private var _stackDisplay:StackDisplay;
private var _visibleAsset:uint;
private var _timer:Timer;
private var _timerTweenOut:Tween;
private var _timerTweenIn:Tween;
public function Main () {
_dataModel = new DataModel();
_stackDisplay = new StackDisplay(_dataModel, this);
configureListeners ();
}
private function configureListeners ():void {
_stackDisplay.addEventListener (Event.COMPLETE, initTimer, false, 0, true);
}
private function initTimer (evt:Event) {
_timer = new Timer(1500);
_timer.addEventListener (TimerEvent.TIMER, timerNext, false, 0, true);
_timer.start ();
}
private function timerNext (evt:Event) {
_timerTweenOut = new Tween(_stackDisplay.assetArray[_visibleAsset], "alpha", Regular.easeOut, 1, 0, 7, false);
_visibleAsset++;
_timerTweenIn = new Tween(_stackDisplay.assetArray[_visibleAsset], "alpha", None.easeOut, 0, 1, 7, false);
}
}
}
Garbage Collection, External SWFs, And XML
I have done TONS of research regarding the AS3 garbage collection issue. I am getting a decent grasp of it, but I CANNOT find any info regarding the removal of xml data. The worst part is, I have no control over the file version (AS2 or AS3) of the swf I am loading. Unfortunately, I am loading AS2 swfs (from an outside vendor that will not show any code) into an AS3 movie. When I run the garbage collection, the xml file/data is not removed and I cannot figure out how to get rid of it. The problem is, once one file is loaded that calls an xml file, no other files can load an xml.
If anyone knows how to clear the XML, please fill me in.
Thanks!
Heather
The code is:
Attach Code
package {
import flash.display.*;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.URLRequest;
import flash.net.LocalConnection;
import flash.system.System;
public class mcConsole extends Sprite {
private var loader:Loader;
public function mcConsole() {
trace("memory: " + (System.totalMemory/1024) + " kiB");
b_0.addEventListener( MouseEvent.CLICK, go_a );
b_0.buttonMode = true;
b_0.mouseChildren = false
;
b_1.addEventListener( MouseEvent.CLICK, go_b );
b_1.buttonMode = true;
b_1.mouseChildren = false
;
b_2.addEventListener( MouseEvent.CLICK, go_c );
b_2.buttonMode = true;
b_2.mouseChildren = false
;
b_3.addEventListener( MouseEvent.CLICK, go_d );
b_3.buttonMode = true;
b_3.mouseChildren = false;
closePres.addEventListener(MouseEvent.CLICK, mark);
closePres.buttonMode = true;
closePres.mouseChildren = false;
loader = new Loader();// Make a new instance of the Loader class
}
public function mark(evt:MouseEvent):void {
trace("memory before CG: " + (System.totalMemory/1024) + " kiB");
loader.unload();
removeChild(loader);
trace(loader);
loader = null;
collectGarbage();
loader = new Loader();
}
// We'll use this function to load an image or swf. Pass it the url to the file
// that will be loaded.
public function load_presentation( u:String ):void {
trace("memory: " + (System.totalMemory/1024) + " kiB");
loader.x = 10;// Position the Loader
loader.y = 50;
addChild( loader );// Add the loader to the display list
loader.load( new URLRequest( u ) );// Load the file
}
public function go_a( evt:Event ) {
/*reset_buttons( evt.currentTarget );*/
load_presentation( "cr/ConsoleA.swf" );// Call load_presentation and pass the url of the file to be loaded.
}
public function go_b( evt:Event ) {
/*reset_buttons( evt.currentTarget );*/
load_presentation( "cr/ConsoleB.swf" );
}
public function go_c( evt:Event ) {
/*reset_buttons( evt.currentTarget );*/
load_presentation( "cr3/ConsoleC.swf" );
}
public function go_d( evt:Event ) {
/*reset_buttons( evt.currentTarget );*/
load_presentation( "cr3/ConsoleD.swf" );
}
/* public function reset_buttons( _mc ):void {// ??? If I pass currentTarget what type is it?
for (var i = 0; i < 4; i++) {
this[ "b_" + i ].enabled = true;// ??? How to disable a button so it is not receiving events?
this["b_" + i].gotoAndStop( "_up" );
}
_mc.enabled = false;
_mc.gotoAndStop( "disabled" );
}*/
public function collectGarbage():void {
try {
new LocalConnection().connect("cr/ConsoleA.swf");
new LocalConnection().connect("cr/ConsoleB.swf");
} catch (e:*) {
}
trace("memory after: " + (System.totalMemory/1024) + " kiB");
}
}
}
Indexed Arrays And Garbage Collection...
Hi everyone,
Im currently trying to put toghether a simple game engine but with enough room in it to be applicable to a fairly complex game.
One of the first issue I have hit is that I have one massive array with all my objects from the world in it. This allows me to easily do per frame processing on them (they all implement a certain interface for this). However, when it comes to removing objects from the world it gets trickier.
The way I have it atm is that new objects are added to the end of the array, unless a slot has been freed up earlier on in the array where an object was destroyed. This give the potential for object references that were good when set up (thingA is shooting at worldArray[25] where worldArray[25] is an enemy), to become bad (thingA is shooting at worldArray[25] where worldArray[25] is now a friendly civilian who was spawned after the tank got blown up and took it's slot in the array... Now I could come up with a complex way of tracking targets and everything but really Id just like to be able to analyse whether some target is dead by saying "if(myTarget == null)" .
So... I need a new solution. My question is as follows:
Can I just keep "push()"ing objects onto the array till the cows come home and keep all the "null" references in place, without taking up an eccessive amount of memory... i.e. when I "null" an object in the middle of an indexed array is its memory space freed up by garbage collection?
Or... do I need another solution? Suggestions and advice welcome.
Edited: 03/16/2008 at 02:53:13 PM by disco-logic
Garbage Collection, Clearing Old Stuff, Etc.
I've got a large memory leak, and am doing some research on actionscript garbage collection. Things have changed since I last did a lot of coding in C++ in college :)
I'm trying to restart my little Flash game level by blowing it away completely and reinitializing it.
Is it true that: with the sweep and mark GC thing that Flash does, all the circular references I have are OK, as long as there is no way to get to stuff I want to delete through any reference chain from the root? e.g., I have a subclassed Sprite object (called _level) that contains everything to do with the game level (graphics, physics engine, in-game objects). Supposedly all I should have to do is removeChild _level from the stage and set _level to null to remove the reference, and everything inside should eventually be cleared by the garbage collector, correct?
All of the movieclips and sprites and other objects I created inside _level will go away eventually, right? Is it true that the only thing that I should be proactive about removing are eventListeners, which, if I understand correctly, will also eventually get garbage collected as well - it's just that they are eating up CPU time getting called until the garbage collector decides that it is time to get rid of them?
Thanks,
Ken
Memory Management / Garbage Collection
Hi.
I have done a lot of searching / reading to find out how to clear my memory. But I still can’t really work out how to clear the memory, it just never seems to come down. I have a few MovieClips that contain other MovieClips with pngs inside them being added to the stage.
As fare as I can tell all Event listeners are removed and refrences
I remove the clip, with removeChild
I "null" the variable
I am using the “LocalConnection()” hack to try and force a clean up, but no movement on the memory count. Are there any examples of a *.png being added and removed from the memory? Or has any one got any more suggestions that could help?
Thanks
AS2 - Importing Classes And Garbage Collection
I'll try to explain this best I can:
I've been working on a few animated demos. I have 4 different demos in 4 different directories - next to each demo fla, I have my com folder and am using a Decorator class for each - com.Demo. So my class name for each is Demo.as, but while working on each one, I have modified the Demo class slighltly for each. Long story short, the classes are different, but named the same.
Due to a client request, I'm now loading each of demos into one shell - so there's a menu where the user can click to load/view the demo they'd like to watch. I've found, after I load the first demo .swf, any subsequent demo that is loaded, is utilizing the first loaded Demo's Class file? As if the first demo that loads - stores a reference to the Demo class in memory - and when other Demos load, it uses that first class versus the Demo.as class that is specific to that swf?
Simple fix is to name the classes different for each Demo - it works great then, but why is this happening? I'm publishing to flash player 8 but have player 9 installed on all my browsers. Is this v9 player specific as I don't think I've run into this before.
Thanks.
Dreaded Topic... Garbage Collection
i have an application that checks an updated XML every 5 seconds. i declare a new XML object within the function and delete it at the end of the function. Some of the XML attributes are saved, but, most of the XML data are ignored if there's no update. There are 4 different main XML childs that I look into to decide whether to ignore it or not.
I do however assign the length of those four childs to a variable and the part that flags if there's an update into an array. Values from that array is then assigned to global variables to be used by other functions.
Would any of these be considered a reference and keep the XML to resign in the memory? I have a feeling that it does since memory usage on the app goes up every 5 seconds even if there is no update.
is there a way to just grab a value of the object without having to reference it?
Layout Class And Garbage Collection
I've been running into some serious memory issues that I'm trying to track down at the moment. For some reason my dynamic swfs that I'm loading never get garbage collected so I'm assuming there is a reference to them somewhere.
I use senocular's layout class so I was wondering if anyone knew steps you need to take to cleanup any objects used in that. For instance when I register a new layout and pass a reference to the display object to be tracked, does that interfere with garbage collection or is it a weak reference?
Garbage Collection, External SWFs, And XML
I have done TONS of research regarding the AS3 garbage collection issue. I am getting a decent grasp of it, but I CANNOT find any info regarding the removal of xml data. The worst part is, I have no control over the file version (AS2 or AS3) of the swf I am loading. Unfortunately, I am loading AS2 swfs (from an outside vendor that will not show any code) into an AS3 movie. When I run the garbage collection, the xml file/data is not removed and I cannot figure out how to get rid of it. The problem is, once one file is loaded that calls an xml file, no other files can load an xml.
The code is:
Code:
package {
import flash.display.*;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.URLRequest;
import flash.net.LocalConnection;
import flash.system.System;
public class mcConsole extends Sprite {
private var loader:Loader;
public function mcConsole() {
trace("memory: " + (System.totalMemory/1024) + " kiB");
b_0.addEventListener( MouseEvent.CLICK, go_a );
b_0.buttonMode = true;
b_0.mouseChildren = false
;
b_1.addEventListener( MouseEvent.CLICK, go_b );
b_1.buttonMode = true;
b_1.mouseChildren = false
;
b_2.addEventListener( MouseEvent.CLICK, go_c );
b_2.buttonMode = true;
b_2.mouseChildren = false
;
b_3.addEventListener( MouseEvent.CLICK, go_d );
b_3.buttonMode = true;
b_3.mouseChildren = false;
closePres.addEventListener(MouseEvent.CLICK, mark);
closePres.buttonMode = true;
closePres.mouseChildren = false;
loader = new Loader();// Make a new instance of the Loader class
}
public function mark(evt:MouseEvent):void {
trace("memory before CG: " + (System.totalMemory/1024) + " kiB");
loader.unload();
removeChild(loader);
trace(loader);
loader = null;
collectGarbage();
loader = new Loader();
}
// We'll use this function to load an image or swf. Pass it the url to the file
// that will be loaded.
public function load_presentation( u:String ):void {
trace("memory: " + (System.totalMemory/1024) + " kiB");
loader.x = 10;// Position the Loader
loader.y = 50;
addChild( loader );// Add the loader to the display list
loader.load( new URLRequest( u ) );// Load the file
}
public function go_a( evt:Event ) {
/*reset_buttons( evt.currentTarget );*/
load_presentation( "cr/ConsoleA.swf" );// Call load_presentation and pass the url of the file to be loaded.
}
public function go_b( evt:Event ) {
/*reset_buttons( evt.currentTarget );*/
load_presentation( "cr/ConsoleB.swf" );
}
public function go_c( evt:Event ) {
/*reset_buttons( evt.currentTarget );*/
load_presentation( "cr3/ConsoleC.swf" );
}
public function go_d( evt:Event ) {
/*reset_buttons( evt.currentTarget );*/
load_presentation( "cr3/ConsoleD.swf" );
}
/* public function reset_buttons( _mc ):void {// ??? If I pass currentTarget what type is it?
for (var i = 0; i < 4; i++) {
this[ "b_" + i ].enabled = true;// ??? How to disable a button so it is not receiving events?
this["b_" + i].gotoAndStop( "_up" );
}
_mc.enabled = false;
_mc.gotoAndStop( "disabled" );
}*/
public function collectGarbage():void {
try {
new LocalConnection().connect("cr/ConsoleA.swf");
new LocalConnection().connect("cr/ConsoleB.swf");
} catch (e:*) {
}
trace("memory after: " + (System.totalMemory/1024) + " kiB");
}
}
}
If anyone knows how to clear the XML, please fill me in.
Thanks!
Heather
Clearing Movieclips Content / Garbage Collection
I have a movie clip that has 20 key frames, and on each key frame is a different bitmap that has been dragged into place from the library. when i attached this, the movie clip play and the memory goes (levels out at the end of the sequens).
But when i remove the movie clip (removeChild) and set the instance to 'null' the memory doesn't come down (even if i wait or force it to garbage collect). Does movie clips content get cleared?
Any help would be very welcome. Thanks
[AS3|Flex2] Variable Usage And Garbage Collection
Quote:
Originally Posted by senocular
When ever there are no longer any references pointing to an object in memory, that object is purged from memory and permanently forgotten by the player.
Code:
delete a; // Object has reference count of 1
delete b; // Object has reference count of 0, removed from memory
Note: remember, the delete operator only removes variable association, it does not delete objects in memory, the GC is responsible for that. Also delete will only work on non class member variables.
Thank You, i also have a question: I have a class called MenuView which contains buttons. After a button from the menu is clicked, its content - which is contained in another class - is being attached to the existing class by the means of the new keyword, so basically it just creates SubClass inside the MenuView class (or instance of another class inside the MenuView Class object if you like):
Code:
_sign_content = new NewEntryView(width);
_sign_content.addEventListener("newEntry_submit", onNewEntrySubmit);
addChild(_sign_content);
NOTE: _sign_content is private property of the class of type NewEntryView (this class contains the content for the button clicked)
Inside this NewEntryView Class (which is being referrenced by the _sign_content property by now), there are textFields being attached to the DisplayList, eventListeners being called, subclasses being created, all that in different functions of the class.
Now when user clicks another button in the menu, i have to set _sign_content=null etc., so that GC can harvest it.
I do so this way from within MenuView class:
Code:
if(_sign_content != null) {
// remove container
removeChild(_sign_content);
// remove variable reference of the object (obj will be removed by GC when there are no referrences on it)
_sign_content = null;
// remove listener
removeEventListener("newEntry_submit", onNewEntrySubmit);
}
However, even after some time, if i had any classes declared in the NewEntryView class (referrenced by the _sign_content variable) - which should be now gone (?), or any Events running (for ex: TimerEvents - so that i can see they're running in the output panel ), these don't get garbage-collected. Neither do variables etc.
So althought i removed all references to the NewEntryView class instance (did i not?), its own variables, methods, listeners - seems DO NOT get removed (getting rid of the refference to the container doesn't get rid of the contents of the container?). When the same menu button is clicked second time, i see duplicate TimerEvents being called along with the old ones, which i want to have destroyed (GC doesnt remove the old ones..).
I have following questions:
1.) Inside the NewEntryView class instance, is it recommended to have a method like ..
Code:
private function removeContent():void {
// removeChild/At on containers
removeChild(_textField1);
removeChild(_sprite2);
......
// null on variables
_tf = null;
_spr = null;
......
// .removeEventListener on event listeners (or weakRef)
this.removeEventListener(TimerEvent.TIMER, onTimer);
// anything else i forgot?
}
.. and call it before removing the refference to the instance of NewEntryView ?
(kind of manual removal.. first getting rid of all the inner pieces of the instance before destroying the shell.. ), or is there an easier way of just removing the shell .. and letting GC to take care of the rest?
2.) EDIT: figured out ([*] read below)
------------------------------------------------------------
If the answer to 1) is YES (dont rely on GC, remove everything manually), that basically means, that i have to keep the referrence to all the variables of the NewEntryView private and available throughout the subclass, and i can't do simply:
Code:
private function createTextField():void {
var tf:TextField = new TextField();
}
.. because i'll loose the reference to the TextField once i jump out of the function (and i can't do removeChild(tf); later)..
Hmm.. ok maybe it can be done other way..
Code:
private function createTextField():void {
var tf:TextField = new TextField();
tf.name = "myTf";
}
....
// and later on
private function removeContent():void {
var tf:TextField = TextField(getChildByName("myTf"));
removeChild(tf);
}
... but i am blabbing already, because i started guessing..
----------------------------------------------------------------
[*] this is not necessary actually (oops i forgot!). Happily AS3.0 now keeps track of all the children objects, so to remove them from DisplayList, its enough to:
Code:
var nCh:uint = this.numChildren;
// trace("children: " + nCh);
for(var i:uint = 0; i < nCh; i++) {
// trace(i, this.getChildAt(0).name);
this.removeChildAt(0);
}
3) I am using Flex2.0. Anybody knows how to work with the Flex2 debugger? (i cant get the variables / objects ..) displayed in the debug panel (?) It would be definitely easier to debug this thing without using trace
Thank Your for Your time ...
... and saying that, i like to hear You people take time for all the other more important things before devoting it to Your reply in this thread
Object Lifespan Within A Scope (Garbage Collection)
Hey all,
So take this basic function:
Code:
public function createNew() {
var myObj = new AwesomeObject();
myObj.setX(30);
myObj.setY(30);
}
Since i'm using the "new" keyword, I'm creating a new Instance of my AwesomeObject and then i'm accessing some of the properties.
However, once i exit the function, I have no way to reference my AwesomeObject instance. Does Flash then consider this garbage? And will then clean it up at some indeterminate time?
Or do I have to explicitly put in another line such as:
myObj = null;
Thanks!
Garbage Collection - Takes Longer And Longer To Occur
We have a kiosk running an 800x600 flash application that loads in external images and data from an external source. (Sometimes quite high rez. e.g. the full 800x600 etc) After many hours the software will die due to running out of RAM. Initial thought were memory leaks. After a lot of research and testing I've found an interesting issue that I think may be a flash bug.
Garbage collection is hard to understand mainly due to the fact that there is no good documentation about how it works (Please Adobe write some somewhere)
The situation is this. The backend holds 200 meg of internal cache and the flash holds up to around 200 meg of images. So all up the software should use between 450- 550 megabyes of ram pretty consistantly.
Now due to the nature of garbage collection the ram will climb and fall back down to the 550meg mark repeatedly as the software runs throughout the day.
The issue I have is that the longer the software runs, the more time seems to pass in between garbage collection passes.
For example. After an hour the garbage collection process sweeps through about once every 60 seconds or so. After 5-6 hours it only seems to sweep through and garbage collect once every 10-15 mins or so. Eventually of course the sweep is hgappening so infrequently that the entire 2 gig of ram gets eaten up and the software dies.
So questions:
1. Is there a way to force garbage collection (I've searched a lot and found nothing but "No's" to this question)
2. How does garbage collection work and why would it become less frequent?
3. Why do we need garbage collection in the first place? Why cant we simply destroy a movie or variable and have it immedialy removed from memory? (True it would require more strict programming but AS3 is strict now anyway)
4. Has anyonce else seen this issue of garbage collection happening less frequently?
5. Can anyone help with my issue?
Edited: 11/21/2007 at 06:39:39 PM by marcus_house
Garbage...
http://board.flashkit.com/board/show...hreadid=371691
|