AS3 Garbage Collection

Hi guys at box3d forums,

using box3d for a physics enabled sidescroller jumpnrun game I've run into a problem: I am having bees (each a body with a circle shape attached in terms of box2d-physics) in one of the levels that are emitted at a high rate at one point and then collected at another point. For the box2d world this means that, when the bee is emitted a CreateBody call is issued and when the bee is collected a corresponding DestroyBody call is done. First everything works fine but after some time the physics become very slow. Are there any known issues with adding/removing a lot of objects into/from the as3-version of the engine?


Andi

P.S.: Apart from the mentioned problem, as3-box3d is FANTASTIC and works like charm for me... 🙂
I am creating and destroying 5-10 bodies a second using sensors as projectiles in AS3 and I don't seem to have any problems. Are you destroying the sprites or bitmaps or whatever you're using for graphics too? I'd have to see any example of how you are coding it probably to know specifically what the problem is. You shouldn't have a problem with garbage collection unless you are getting rid of a big chunk of memory all at once, and then it might freeze for a second. As long as you are destroying objects steadily I think it should work fine. Do you have it displaying memory used while you are testing?
Are you more used to C++ style garbage collection? If so, you should be warned that AS3 garbage collection works differently.

b2World.DestroyBody only removes the internal pointers to a body, it doesn't automatically free the memory, unlike C++. i.e.
Code:
var body:b2Body=m_world.CreateBody(def);
globalMyBody=body;
m_world.DestroyBody(body);
in AS3 leaves body in memory, and globalMyBody a valid reference. While
Code:
b2Body body=m_world.CreateBody(def);
globalMyBody=body;
m_world.DestroyBody(body);
in C++ removes the body from memory, and globalMyBody is a invalid reference.


BTW it's box2d, even the Flash version, which is officially Box2DFlashAS3.
You can use flash.system.System.totalMemory to see if it is memory usage that's causing it. However it's almost definately not the engine.
Hey, thanks to all of you for your information. But I found out, that it was not really box3d that was leaking but my own code 😳. Box2d seems to destroy the bodies perfectly.

But there are weird issues with as3 (flash player 9) garbage collection. Objects normally get collected as soon as there are no more references to them this however does NOT apply to Sprites and MovieClips that have registered an enterframe-EventListener (even if its a weak one).

Took me hours to figure out... 😀

here's a link to some as3-guru dealing with those problems (for anyone interested)
http://www.gskinner.com/blog/archives/2 ... ce_ma.html


thanks again for your help

Andi
@BorisTheBrave:

LOL, ok, of course boxTWOd, maybe I'd just love real 3d in flash....
@superandi:

Yeah GC in Flash can be really annoying. Can't believe all we have to force GC is an ugly hack! Excuse me for trying to program an action game Adobe! If I could just have it get everything out of the way inbetween levels it would make things really solid. I ran into problems with GC recently too (yesterday!), so I thought I'd share the experience. Even though I'm still not sure quite what to make of it.

Ok so I am finishing up a game in AS3 and I notice now that I've really gotten into building levels that every time I load a new level I leak about 5MB! This came as a surprise to me, because I have specifically nulled my b2World, my Level object, etc... So I figured I missed a reference somewhere. Some hours later, after cleaning up a bunch of stuff and making ABSOLUTELY CERTAIN that I was not referencing my b2World somewhere I find that it's still happening! I found that creating my b2World was where the jump in memory happened, and then it would never go back down. So I though maybe Box2DAS3 had a leak, looked around at the code and I doubt it, so...

I try forcing GC with the localConnection hack method. That got rid of a few MB, which is weird because I kept restarting the level to see how much memory I would rack up (without the hack) and it got over 150MB!! So it apparently was getting rid of something with forced GC that it never did otherwise. This is tested with standalone flashplayer and in browser.

The leak is still there. So I figure if the b2World won't die quietly I will have to beat it to death! So I attempt to explicitly delete all the stuff in the b2World like so:

Code:
   var next:b2Body = world.m_bodyList;
   var current:b2Body;
   while (next != null) {
      current = next;
      next = next.m_next;
      world.DestroyBody(current);
      current = null;
   }
         
   world.m_broadPhase = null;
   world.m_contactManager = null;
   world.m_bodyList = null;
   world.m_contactList = null;
   world.m_filter = null;
   world.m_jointList = null;


This seems to help a little, but still a leak!

So the leak is still there, though apparently a little smaller?!!! So I decide to try the memory profiler in the Flex 3 Beta. I run the profiler and it says peak memory after restarting levels about 20 times is.... 21MB?????? WTF!! So it's telling me basically that I don't have a memory leak... This is within the expected memory usage for my program (everything is drawn with BitmapData, so it caches rotations and stuff). I should add that I have only 1 instance of flashplayer running at any time, no other tabs or browsers, because I know the memory readout in Flash (from System) will read out the total for all instances of flashplayer. Meanwhile my Flash app is reading out like a gazillion MB (ok it was more like 165MB). I'm assuming it has something to do with running the profiler wackyness. Even running in browser with the hack I can still get well above 150MB though.

I really don't know what to make of this, but I will probably keep restarting the level until I get like 800MB used just to see what happens at some point (I have 1GB and running XP, so that should get laggy). The only thing I can think of is that the memory readout has some weird bug. This is the code I'm using to read out memory, so I'm not adding to some variable or anything weird:

Code:
   var memused:String = new String();
   memused = Math.round(System.totalMemory/1048576) + " MB used";


I guess I just won't worry about it much for now. Like I said, I don't have any real conclusion except that I don't trust the System.totalMemory anymore! I don't necessarily trust the profiler either though... Hopefully this experience is useful to someone, and maybe others have stories to share, or will at some point. I would love to hear them!
Hi Brainclog,

what I figured out regarding these AS3 Garbage Collection Issues is the following:

Box2d is not the problem, the problem are enterframes, timers and movieclips.

The normal way of as3s garbage collector is: if there are no references to an object it will be deleted. This is true most of the time but NOT for DisplayObjects that dispatch "enterFrame" events to one or more listeners. Even if the listener reference is a weak one and the object containing the event handler gets collected the dispatcher is kept alive. Thje same applies to timer objects. This means we can have DisplayObjects and Timers completely isolated with not a single reference pointing to them that still do not get collected.

Another problem are MovieClips ( i only tried clips loaded from swfs) what i saw was this: The clips ar "playing" by default. and playing movieclips do not get collected either. If you stop them first they get thrown away and the memory is freed.

You can see exactly which objects get collected by building a Dictionary-Object with weak keys and storing the objects you want to watch in this object as keys. list the objects in the Dictionary in certain intervals yand you will see which objects are still there.

The problem is that if in your displaylist is one of these bad boys and you detach the top level object, null all references your entire scene will not be collected (i guess because of the "parent" refernece in each displayobject) and you end up having your whole gaming history of levels monsters etc silently living on in memory.

So what can we do? I did the following:

- no local enterframes: I register all needed enterFrame events as weak Refernces with the stage.

- explicitly stop all timers, or even better use a iterations count in the timers constructor (xyz=new Timer(1000, 5) if possible.

- stop all movieclips (xyz.stop())

- only use weak references in event listeners (except very rare cases I cant really think of 🙂)

oh by the way, in the new Flex 3.0 sdk there is now a function called flash.system.System.gc() that forces garbage collection. I use that now instead of the good old localConnection hack.


Good luck & happy collecting
Thanks, that was some good info! I had read some of that stuff before, but nice to have it all explained in one place. The best part is, I think my memory leak is fixed! This makes me even more confused about the profiler telling me 21MB though. I was reading through what you said and didn't think it applied to my code, until I started thinking about timers.

I use quite a few timers, but they are almost all set numbers of iterations. Then I remembered that I have this ONE timer for these sentry gun things so that it can only fire every x ms. That timer was it! The whole problem was a SINGLE TIMER!!! I just restarted levels like 20 times and memory stays the same. The sentry gun isn't even in every level, but it gets created anyhow and then destroyed because of how my tile system is set up. So I was getting a timer in every level that was causing the entire level to stick around!

Your post really gave me that extra push I needed to examine my code. I owe you one!

EDIT: I wanted to mention that the new gc() function apparently only works with AIR and the debug version of Flashplayer. So really we still have no way to do GC but the hack for production work (unless it's AIR).

see the docs
From the docs:

Quote:
gc() method
public static function gc():void

Language Version : ActionScript 3.0
Player Version : Flash Player 9.0.115.0

Forces the garbage collection process.

For the Flash Player debugger version and AIR applications only. In an AIR application, the System.gc() method is only enabled in content running in the AIR Debug Launcher (ADL) or, in an installed applcation, in content in the application security sandbox.


You can't count on System.gc() being around in AIR applications all the time, either. Just a heads up.

Original thread: https://box2d.org/forum/viewtopic.php?t=503