Haxe Map Memory Cleanup Issue - actionscript-3

So I have been using Haxe for a while and it has occurred to me recently that I don't really get what happens on some other the non-flash targets as far as memory cleanup. I mean 'new'ing everything and dumping it by setting references to null gives me this feeling that there are memory leakages, but I can't seem to find the documentation I'm looking for.
Specifically I use dictionaries/maps a decent amount. Like this:
var items:Map<String, MyObject> = new Map();
items.set("someKey", new MyObject(args...));
// Later
items["someKey"].doSomething();
items["someKey"].setVal(2);
...
// When Finished
items.remove("someKey");
The last line there just dumps my object somewhere into oblivion and hopefully gets garbage collected (at least on the Flash target).
I put together a little program just to see the cleanup in action on Flash/Neko and then change it for other targets, but I am failing to even see the cleanup on the Flash Neko target. Here is the project code:
package;
import openfl.display.Sprite;
import openfl.events.Event;
import haxe.ds.StringMap;
import openfl.events.KeyboardEvent;
import openfl.ui.Keyboard;
class Main extends Sprite
{
private var keypressID:Int;
private var itemID:Int;
private var dict:StringMap<Sprite>; // Using this since I read Map<String, T> just compiles to StringMap<T>.
public function new()
{
super();
addEventListener(Event.ENTER_FRAME, init);
}
private function init(event:Dynamic):Void
{
removeEventListener(Event.ENTER_FRAME, init);
// Entry point.
keypressID = 0;
itemID = 0;
dict = new StringMap();
stage.addEventListener(KeyboardEvent.KEY_UP, keyPress);
}
private function keyPress(event:Dynamic):Void
{
if (Std.is(event, KeyboardEvent) && cast(event, KeyboardEvent).keyCode == Keyboard.A)
{
trace('ID: $keypressID - Adding Item');
keypressID += 1;
for (i in 0...10000)
{
itemID += 1;
dict.set('$itemID', new Sprite());
}
}
else if (Std.is(event, KeyboardEvent) && cast(event, KeyboardEvent).keyCode == Keyboard.R)
{
trace('ID: $keypressID - Removing Items');
keypressID += 1;
removeItems();
}
// Force garbage collector to run.
else if (Std.is(event, KeyboardEvent) && cast(event, KeyboardEvent).keyCode == Keyboard.C)
{
trace('ID: $keypressID > Starting GC');
keypressID += 1;
forceGarbageCollection();
}
}
private function removeItems()
{
trace('ID: $keypressID > Remove All Item');
for (val in dict.keys())
{
dict.remove(val);
}
dict = new StringMap();
}
private function forceGarbageCollection():Void
{
neko.vm.Gc.run(true); // This does not work.
}
}
I run this on Windows and under task manager, my neko process only grows and never shrinks. Its gets up to 500MB quick when hitting 'A'. I then 'R' to remove all references to the items, but they never get collected it seems even when I force the GC.
I also tried storing openfl.util.Timer objects with event listeners attached to them to do traces and they never seem to get collected either. They just keep tracing. Now I suspect that may be because of the event listener reference, but am sure I have seen that trick in other AS3 memory leak tracking code.
Am I missing something or doing something wrong?
Edit:
I have modified the above question to reflect this, but I was mistaken about Flash player. I did get the memory to be reclaimed when running in the Flash player using flash.system.System.gc(); It seems the problem may be specific to neko which my question still addressed.

Related

What can I use instead of Timers to help my performance?

My app is very slow on mobile devices.
It uses a lot of Event.ENTER_FRAME event listeners, so I switched (as I read they are much more performance heavy) to a global timer that these classes listen for if they need to update (they only use these timers if they have been initiated by a TouchEvent).
I also tried enabling hardware acceleration, and switching to using the CPU, but these have not helped with the lag issues to a noticable amount. (my app has very few animations so I think this is the best decision)
I do have a lot of MovieClips in it, however very few of them actually animate, so I doubt this is an issue. (This is also why I do not freeze and unfreeze objects, as they are never removed from the stage)
On this website they said the following about timers
– the more timer instances linger in the system, the more you can expect slow and choppy gameplay or unresponsive UI.
I only use one timer, so I didn't think this would be an issue, but I do have a lot of event listeners that use this timer to update, so I can only figure that the timer must be the issue. Thus to avoid lag I am looking for a better alternative.
To be clear, I'm not using many Event.ENTER_FRAME event listeners anymore, I've mostly switched to timers. With that being said, here is an example of a more resource demanding one.
package
{
import flash.display.MovieClip;
import flash.events.Event;
public class mc_BattleScene extends MovieClip
{
public static var mc_PlayerFace:MovieClip;
public static var enemyAttackEffect:MovieClip;
public static var mc_playerHitBox:MovieClip;
public static var battler1:Number = 1;
public static var battler2:Number = 1;
public static var battler3:Number = 1;
public var lvlModifier:Number;
public var dmgReduction:Number;
public var dmgDealt:Number;
public static var dmgSpeed:Number = 1;
public function mc_BattleScene()
{
visible = false;
addEventListener(Event.ENTER_FRAME, onFrame);
mc_PlayerFace = playerFace_mc;
enemyAttackEffect = attackEffect_mc;
mc_playerHitBox = playerHitBox_mc;
function onFrame(e:Event):void
{
battler1_mc.gotoAndStop(battler1);
battler2_mc.gotoAndStop(battler2);
battler3_mc.gotoAndStop(battler3);
if (Game.playerInteractionStatus[1])
{
//we are fighting
visible = true;
if (attackEffect_mc.hitTestObject(playerHitBox_mc))
{
// attack hit us, deal dmg
dmgReduction = (Game.playerStats[2] * (Game.enemyStats[1]));
dmgDealt = Game.enemyStats[1] - dmgReduction;
attackEffect_mc.x = 516;
if (Game.playerStats[0] - Math.round(dmgDealt) <= 0)
{
// round dmg to 0 (were dead)
Game.playerStats[0] = 0;
}
else
{
// deal damage to us
Game.playerStats[0] -= Math.round(dmgDealt);
}
}
else if(attackEffect_mc.hitTestObject(wall))
{
//stop the player from moving (by doing nothing)
}
else
{
attackEffect_mc.x -= dmgSpeed;
}
}
else
{
// reset the position of the attack effect if we are not fighting
visible = false;
attackEffect_mc.x = 516;
}
}
}
}
}
This example of Event.ENTER_FRAME is one of the few that actually are this complicated, the other Event.ENTER_FRAMEs tend to simply update values (ex: update a text field to display correct number variables)
For example: creating multiple vars inside an enterframe could clog
the memory and cause lag.
I've avoided doing stuff like this, as not only what you've said, but in my opinion I think it doesn't make sense to continuously define it in a function, I update these values only.
Resources
http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-8000.html
max links allowed

AS3 Memory Management reverse engineering

Has anyone figured out how AS3 actually handles garbage collection? I'm having so many issues releasing memory in a game I'm developing.
Made a small demo:
public class MemoryTesting extends Sprite
{
static protected var list:Array = null;
public function onKeyDown(event:KeyboardEvent):void {
if( event.keyCode == 65 ){ //A key - adds memory
if( list == null ){
list = [];
for( var index:int = 0; index < 10000000; ++index ){
list.push(new Matrix3D());
}
}
}
else{ //Any other key removes memory.
if( list ){
var size:int = list.length;
for( var index:int = 0; index < size; ++index ){
list.pop();
}
list.length = 0;
list = null;
}
System.gc();
}
}
}
Running Flash Player Debugger stand-alone 11.4r402 in Windows 7. Watching the Task Manager, with no keys pressed, the debugger sits idle at 11,000 K.
Pressing a (adding 10Mil Matrix3D classes) takes it up to 962,000 K.
Pressing another key (removing references to the Matrices and nulling the array) depends on how many times I press it.
The first time we call GC - drops to 255,000 K.
The second GC call - 92,000 K.
Third - 52,000 K.
Forth - 42,000 K.
Fifth - 39,000 K.
Sixth & any consecutive times after sits at 38,000 K.
I hear people talking about the GC waiting for "opportune times" to collect. But this is an empty application, not even a enter_frame event and there is no amount of time you can leave it idle for it to remove the remaining 27,000 K (38,000 - 11,000).
Sitting at the new low, if we re-add the matrices we move back up to 975,000 K.
That is to say, 13,000 K more than the first time. If I repeat this add/remove, it stays the same, going back up to 975,000 K and down to 38,000 K.
Remember, there is nothing going on in this application. My actual application has 650mb of raw bitmap data, let alone 100mb of SWF to parse and 500mb of XML classes that I only use in initialisation code.
I've read multiple times that even calling GC manually is bad, let alone 6 times. But none of the Matrix3D's will be released if I don't.
How does anyone handle this? Shall I just call GC 6 times at the end of initialisation?
Edit:
I was testing in release mode for differences and whether, without the System.gc() call, that if it doesn't free the memory from flash, at the least re-uses it properly. It does eventually, but with a new, higher footprint. With a full list sits at 990,000 K, clearing it takes it to 1,050,000 K.
This is for data that initially cost us 962,000 K RAM. That's 90MB of weird internal flash GC memory. Let alone ignoring that it won't ever give the memory back to the OS (without the explicit GC calls).
Actionscript's GC is weird, nothing to say,
If you'll try to use something like this, it helps (I just tested and GC clears out the memory on the very first try (key click)), Just changed Array to Vector to test more quicker, just the same should happen with Array too. My enviroment is FlashCC in this case.
package
{
import flash.display.Sprite;
import flash.events.KeyboardEvent;
import flash.geom.Matrix3D;
import flash.net.LocalConnection;
import flash.system.System;
import flash.utils.setTimeout;
public class MemoryTesting extends Sprite
{
var list:Vector.<Matrix3D> = null;
function MemoryTesting()
{
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
}
public function onKeyDown(event:KeyboardEvent):void
{
var matrx:Matrix3D;
var index:int
if (event.keyCode == 13)
{
trace(System.totalMemory, "starting to fill...")
if (list == null)
{
list = new Vector.<Matrix3D>
for (index = 0; index < 1000000; ++index)
{
matrx = new Matrix3D();
list.push(matrx);
}
}
trace(System.totalMemory, " done...")
}
else
{
if (list)
{
trace(System.totalMemory, " preparing to delete...")
list.splice(0, list.length);
list = null;
}
//force GC to work normally, it really helps (at least in my case)
try
{
new LocalConnection().connect('foo');
new LocalConnection().connect('foo');
}
catch (e:*)
{
}
setTimeout(function()
{
trace(System.totalMemory, " deleted")
}, 50)
}
}
}
}
This strange snippet really helps on most cases
try {
new LocalConnection().connect('foo');
new LocalConnection().connect('foo');
} catch (e:*) {}
Here is the freat article:
http://gskinner.com/blog/archives/2006/08/as3_resource_ma_2.html

addEventListener and memory leak

Im doing a small game for college work and I don't understand very well how the garbage collector works
with EventListeners, I feel that the "preCastTimer" EventListener never gets removed on the code below. The problem is that I have no idea how to remove it once its complete.
below is the code Im using to cast a spell when a key is pressed
Here I have the casting functions called by KeyboardEvents, fireball is a MovieClip
preCast(fireball);
function preCast(spell)
{
var tempSpell:Object = new spell;//create an object for the spell so castTime is accessible.
var preCastTimer:Timer = new Timer(tempSpell.castTime,1);
var spellFunc:Function = cast(spell);
preCastTimer.addEventListener(TimerEvent.TIMER_COMPLETE, spellFunc);
preCastTimer.start();
}
function cast(spell):Function {
return function(e:TimerEvent):void {
parent.addChild(new spell);//For some reason if spell is not created here it never gets a parent
};
}
Here is the code for the fireball MovieClip:
package {
import flash.display.MovieClip;
public class fireball extends MovieClip {
public var castTime:uint = 1000;
public function fireball() {
// constructor code
}
}
}
The code below is in the fireball timeline. I understand it's better to use class, but I still don't understand parenting when the code is in the package and not on the timeline frame
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.geom.Point;
if (parent)//only run if a parent exists, when created as object no parent is defined
{
x = parent.getChildByName("player").x;
y = parent.getChildByName("player").y;
var direction = new Point(parent.mouseX - x,parent.mouseY - y);
rotation = Math.atan2(parent.mouseY - y,parent.mouseX - x) * 180 / Math.PI;
direction.normalize(5);
if (direction.x == 0 && direction.y == 0)
{
parent.removeChild(this);
return;
}
var spellTimer:Timer = new Timer(500,1);
spellTimer.addEventListener(TimerEvent.TIMER_COMPLETE, spellKiller);
this.addEventListener(Event.ENTER_FRAME, motion);
spellTimer.start();
}
function spellKiller(e:TimerEvent):void
{
this.removeEventListener(Event.ENTER_FRAME, motion);
spellTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, spellKiller);
parent.removeChild(this);
}
function motion(e:Event)
{
x += direction.x * 5;
y += direction.y * 5;
}
Notice that addEventListener has the useWeakReference argument (5th argument).
public function addEventListener(
type:String,
listener:Function,
useCapture:Boolean = false,
priority:int = 0,
useWeakReference:Boolean = false
):void;
From the EventDispatcher documentation:
If you no longer need an event listener, remove it by calling
removeEventListener(), or memory problems could result. Event
listeners are not automatically removed from memory because the
garbage collector does not remove the listener as long as the
dispatching object exists (unless the useWeakReference parameter is
set to true).
The solution would be to simply convert your addEventListener calls to use weak references, where appropriate.
foo.addEventListener(type, listener, false, 0, true);
Please let me know if you're not sure how this helps you.
So your code is a bit overly complicated with some important parts missing so I cannot really comment on that parent thing. As far as I understand the timer should fire once and then you want its listener removed, correct? Well, that's pretty easy to achieve:
function cast(spell):Function {
return function(e:TimerEvent):void {
parent.addChild(new spell);
e.target.removeEventListener(TimerEvent.TIMER_COMPLETE, spellFunc);
};
}
Why do you have the feeling that this is not the correct solution? You can test that the listener is removed by simply changing the TimerEvent.TIMER_COMPLETE to TimerEvent.TIMER (and removing the repeat count passed to the constructor of your timer). It should add the spell once and no more.
Also note that the garbage collector will not pick it up right away (well, very probably not!). It may pick it up somewhere in the future or never. Actually, the timer will probably never get picked if you don't set it to null or you don't create another timer object and assign it to the same variable as your reference will remain and therefore it will never get eligible for garbage collection.

Anonymous functions as event handlers in Action Script - good or bad?

I came to AS3 from JS world, and I should confess that anonymous functions are my weakness. I tend to use them everywhere. Now, coming to AS3 I've heard and read in lots of places, that AS and Flash are enormously bad at handling garbage collection, that one should empty, dispose and remove all event handlers and objects manually to avoid weird and unexplainable memory leaks and crashes. Not sure what part of this is true, but I would like to follow best practices right from the beginning.
So my question would be - how bad is idea of using anonymous functions as event handlers? Consider for example a code like this:
addEventListener(Event.ENTER_FRAME, function() : void {
controls.elapsed = stream.time;
});
contorls.elapsed is the setter, which apart from setting current play time for video player, updates the whole UI, and stream is NetStream object, which streams the actual video.
There are lot's of other places where anonymous function may make code cleaner and more intuitive. Check the following code for simple fade-in effect for the control bar:
public function showControls() : void
{
var self:Controls = this;
if (!visible) {
visible = true;
fadeTimer = new Timer(30, 10);
fadeTimer.addEventListener(TimerEvent.TIMER, function() : void {
self.alpha += 0.1;
});
fadeTimer.addEventListener(TimerEvent.TIMER_COMPLETE, function() : void {
self.alpha = 1;
});
fadeTimer.start();
}
}
I totally like how it looks and fits into the code, but I'm concerned about leaks. While Event.ENTER_FRAME handler probably would never become harmful in this form, what about timer listeners. Should I remove those listeners manually, or they will be removed automatically, as soon as I set fadeTimer = null ? Is it possible to remove listeners with anonymous functions properly at all?
Just noticed this post -- there are a couple things that might be of use to you. One is arguments.callee (which is a reference to the current function you're in). This is useful for removing references in anonymous functions. Also, it could be noted that you could use weak references in your addEventListener code -- however, this won't work for variables that are anonymous, as they'd get GC'd pretty much immediately. For simplicity sake I rewrote your code like this: (should work -- haven't tested)
private function showControls() : void {
if (visible) {
return;
}
var self:DisplayObject = this;
var fadeTimer= new Timer(30,10);
var handler = function(e:Event) {
switch (e.type) {
// timer complete
case TimerEvent.TIMER_COMPLETE:
// remove references to this anonymous function -- for garbage collection
fadeTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, arguments.callee);
fadeTimer.removeEventListener(TimerEvent.TIMER, arguments.callee);
// break out
return self.alpha = 1;
// timer
case TimerEvent.TIMER:
return self.alpha += 0.1;
}
}
fadeTimer.addEventListener(TimerEvent.TIMER, handler);
fadeTimer.addEventListener(TimerEvent.TIMER_COMPLETE, handler);
fadeTimer.start();
}
I would do it something like this. And, be sure to use dispose() when you want to make sure to clear the timer if interrupting.
private function showControls() : void
{
if(_isVisible)
return;
// start you control here
_fadeTimer = new Timer(30, 10);
_fadeTimer.removeEventListener(TimerEvent.TIMER, updateFade);
_fadeTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, updateFadeComplete);
_fadeTimer.start();
}
private function updateFade(event : TimerEvent) : void
{
// update fade here
}
private function updateFadeComplete(event : TimerEvent) : void
{
dispose();
}
private function dispose() : void
{
if(_fadeTimer)
{
_fadeTimer.stop();
_fadeTimer.removeEventListener(TimerEvent.TIMER, updateFade);
_fadeTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, updateFadeComplete);
_fadeTimer = null;
}
}
There's nothing wrong with using function methods where it works. As far as memory leaks go, you need to track the object to the stage to see if it can be removed.
Adding an ENTER_FRAME event handler to the control ensures that the control has a reference to the anonymous function. As the code is part of the control (or so it appears), this is fine as the anonymous function will be removed when the control is.
Adding an event handler to the timer ensures that the timer has a reference to the anonymous function. If the timer is running, it will keep the anonymous function reference alive and, by association, the enture control. Once the timer has stopped, however, both it and the function should be collected.
If all else fails, use the profiler and see! ;)

Controlling FPS of a loaded swf

I'm working on a flash app where I load multiple swf's. But the problem is that they have different framerates (12/25/30). If I add 2 swf's they both play at 25fps. I found numerous topic about this but I can't get it to work (in AS3). Does anyone know why it doesn't work and how to make it working?
public class MainClass extends MovieClip
{
var loader:Loader = new Loader();
var request:URLRequest;
var mcMedia:MovieClip = new MovieClip();
MovieClip.prototype.setFrameRate = function(frameRate:Number)
{
var mc:MovieClip = this;
if (mc.tweenFaster != null)
{
Timer(mc.tweenFaster).stop();
}
mc.tweenFaster = new Timer(1000/frameRate);
mc.tweenFaster.addEventListener(TimerEvent.TIMER, timelineFaster);
mc.tweenFaster.start();
function timelineFaster(event:TimerEvent = null)
{
if (mc.currentFrame == mc.totalFrames)
{
mc.tweenFaster.stop();
mc.gotoAndStop(1);
}
else
{
trace(mc.currentFrame);
mc.nextFrame();
}
event.updateAfterEvent();
}
}
public function MainClass()
{
configureListeners();
request = new URLRequest("data/7/7.swf");
try
{
loader.load(request);
}
catch (error:Error)
{
trace("Unable to load requested document.");
}
}
private function configureListeners():void
{
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
loader.contentLoaderInfo.addEventListener(Event.OPEN, openHandler);
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler);
loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
loader.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}
private function completeHandler(event:Event):void
{
loader.content.scaleX = 550/event.target.width;
loader.content.scaleY = 400/event.target.height;
mcMedia.addChild(loader);
mcMedia.setFrameRate(12);
addChild(mcMedia);
}
In as3, if you're just looking to change the framerate, use stage.frameRate = 12; or whatever;
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/Stage.html#frameRate
In AS3, while you can use prototypes, you generally don't. I'd rewrite your setFrameRate function (which is badly named, shouldn't it be more.. tweenFaster, or matchFrameRate or something?)
I'd make a helper function like this:
package util{
//imports
public class TweenFasterMC extends MovieClip{
public var mc:MovieClip;
public function matchFrameRate(frameRate:Number):void
{
if (tweenFaster != null)
{
Timer(mc.tweenFaster).stop();
}
tweenFaster = new Timer(1000/frameRate);
tweenFaster.addEventListener(TimerEvent.TIMER, timelineFaster);
tweenFaster.start();
}
function timelineFaster(event:TimerEvent = null):void
{
if (currentFrame == totalFrames)
{
tweenFaster.stop();
gotoAndStop(1);
}
else
{
trace(currentFrame);
nextFrame();
}
event.updateAfterEvent();
}
}
Also, clean up your event listeners, that strong timer event listener will cause a lot of problems if you have a lot of mc's your applying this functionality to.
As far as I know all MovieClips in one flash player instance (sharing the same 'stage') will run at the same speed - there is no way to have two clips running at different speeds. So to adjust the speed you have to resort to calling gotoAndStop() on all MovieClips in the loaded clip at the right time - that won't be fun.
Code along the lines that quoo is showing will only work if the loaded swf contains just 1 MovieClip (no nesting) as far as I can see.
It seems to me that the most likely reason why this wouldn't work is that it requires every clip you load to be a simple, completely non-dynamic animation that loops for ever. If the loaded content is that simple, why not just adjust it to look better at 30fps? (If it's extremely long, a JSFL script could automate the process of adding extra frames.) Alternately, if the content isn't that simple, then attempting to change its timing by calling nextFrame from elsewhere is not going to give you what you want.
With all that said, if you're sure this is what you want to do but you're getting 0 as a return for currentFrame in your loaded content, are you sure they are AS3 SWFs? If they aren't, AS3/AS2 interoperation is a hairy subject that will warrant reading up on.
This is a real hassle, I've been scouring the net for an answer. I have particles following a path, and I want to change the speed that these particles follow the path dynamically, without changing the whole movie. just the particles movie clip.
I've tried greensock, but, that doesn't really work like i need.. i'd think there would be something that you can change dynamically for each mc, but, no dice.
the stage.frameset is only for the whole movie... argggggggg..... sucks..