gabage collect example

by pleclech
♥0 | Line 49 | Modified 2011-02-20 22:46:07 | MIT License
play

ActionScript3 source code

/**
 * Copyright pleclech ( http://wonderfl.net/user/pleclech )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/uP5T
 */

package {
    import flash.text.TextField;
    import flash.utils.Dictionary;
    import flash.system.System;
    import flash.events.KeyboardEvent;
    import flash.events.Event;
    import flash.display.Sprite;
    public class SO_GC extends Sprite {
        private var notGC:Dictionary=new Dictionary(true)
        private var tf:TextField=new TextField()
        public function SO_GC() {
            // write as3 code here..
            if (stage) _init()
            else addEventListener(Event.ADDED_TO_STAGE, _init)
        }
        private function trace(...args):void{
            tf.appendText(args.join(", ")+"\n")
        }

        private function _init(e:Event=null):void {
            removeEventListener(Event.ADDED_TO_STAGE, _init)
            addChild(tf)
            tf.autoSize="left"
            tf.background=true
            trace("push a key to see what have not been garbage collected\n")
            stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown)

            test()
        }
        public function traceNotGC():void{
            var cnt:int=0
            for (var key:Object in notGC) {
                cnt++
                trace("not garbaged : " + key)
            }
            if (cnt==0) trace("All garbaged")
        }
        public function onKeyDown(e:Event):void{
            System.gc()
            traceNotGC()
        }
        public function test():void{
            var str:String="not dead"  // string taken from the constant pool
                                       // there is no allocation done
                                       
            var obj:Object={foo:"bar"} // creation of a new object that can be garbaged
            var arr:Array=[0,1,2]      // creation of a new array that can be garbaged
            
            notGC[str]=true
            notGC[obj]=true
            notGC[arr]=true

            traceNotGC()
        }
    }
}