当前位置:主页>FLASH AS 编程>AS小技巧>文章内容
  • ActionScript 3.0中的垃圾回收
  • 来源:flashxm.com 作者:flashxm 2008-07-03 【
FlashAs作品发表>>我要投稿 | FlashAs讨论区>>AS论坛
Flash Media Server学习站>>www.FMScn.com


众所周知,在as3的flash运行器中新增了垃圾回收的机制,即自动从内存中清除一些不可访问的对象。这个过程我们是无法控制的,不过可以通过一个例子来观察这个过程:

  1. package
  2. {
  3.     import flash.display.Sprite;
  4.     import flash.text.TextField;
  5.     import flash.utils.Timer;
  6.     import flash.events.Event;
  7.     import flash.events.TimerEvent;
  8.     import flash.system.System;
  9.     public class GarbageCollection extends Sprite
  10.     {
  11.         public function GarbageCollection()
  12.         {
  13.             var s:Sprite = new Sprite;
  14.             s.graphics.beginFill(0, 1);
  15.             s.graphics.drawRect(0, 0, 100, 100);
  16.             //addChild(s);
  17.             s.addEventListener(Event.ENTER_FRAME, enterframelistener);
  18.             var timer:Timer = new Timer(1);
  19.             timer.addEventListener(TimerEvent.TIMER, timelistener);
  20.             timer.start();
  21.         }
  22.         private function timelistener(e:TimerEvent):void
  23.         {
  24.             new TextField();
  25.         }
  26.         private function enterframelistener(e:Event):void
  27.         {
  28.             trace('Flash Player当前所用内存(字节):', System.totalMemory);
  29.         }
  30.     }
  31. }

当输出窗口停止输出信息时就意味着在构造方法中创建的局部变量s被当成垃圾给回收了。

如果将addChild(s)取消注释,s就会被放到场景中,从而不被回收。系统转而回收timelistener里创建的n多没用的new TextField,可以看到:
…省略…
Flash Player当前所用内存: 3403776 字节
Flash Player当前所用内存: 3407872 字节
Flash Player当前所用内存: 3420160 字节
Flash Player当前所用内存: 2142208 字节
Flash Player当前所用内存: 2146304 字节
…省略…
很明显可以看到垃圾回收的过程。

ps: 此例原型是Essential ActionScript 3.0 P277的Example 14-1. Garbage collection demonstration





上一篇:Flash程序的测试方法   下一篇:在 ActionScript 3.0 中偷懒
  • 用户名:新注册) 密码: 匿名评论
  • 评论内容:(不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规)

Copyright © 2006-2008 flashas.net All Rights Reserved.
网站内容咨询: admin#flashas.net (#为@) 联系QQ:40777822 浙ICP备06033001号
(本网站最佳浏览解析度为1024*768, 建议使用IE 6.0或以上版本浏览器。)