[转载]AS3强制内存回收的方法
注:AVM的GC机制确实有些诡异,不象CLR可以通过GC.Collect()显示调用,中午在天地会闲逛时,发现了下面的这二个方法,转载一下
方法1:
1 |
function GC(): void { |
2 |
try { |
3 |
( new LocalConnection).connect( "foo" ); |
4 |
( new LocalConnection).connect( "foo" );} catch (e){ |
5 |
trace (System.totalMemory); |
6 |
} |
7 |
} |
方法2:
01 |
package { |
02 |
/** |
03 |
* @author CYPL |
04 |
* @date 2009-04-01 |
05 |
*/ |
06 |
import flash.net.SharedObject; |
07 |
import flash.system.System; |
08 |
import flash.utils.clearInterval; |
09 |
import flash.utils.setInterval; |
10 |
|
11 |
public class GCPlus { |
12 |
public static function clear(isTraceTM : Boolean = false ) : void { |
13 |
var time : int = 2 ; |
14 |
var interval : int = setInterval(loop, 50 ); |
15 |
function loop() : void { |
16 |
if (!(time--)) { |
17 |
isTraceTM && trace (System.totalMemory); |
18 |
clearInterval(interval); |
19 |
return ; |
20 |
} |
21 |
SharedObject.getLocal( "cypl" , "/" ); |
22 |
} |
23 |
} |
24 |
} |
25 |
} |
测试代码:
01 |
package { |
02 |
import flash.display.MovieClip; |
03 |
import flash.display.Sprite; |
04 |
import flash.events.MouseEvent; |
05 |
import flash.system.System; |
06 |
|
07 |
/** |
08 |
* @author CYPL |
09 |
*/ |
10 |
public class GC_Test extends Sprite { |
11 |
private static const NUM : int = 1000 ; |
12 |
private var num : int ; |
13 |
|
14 |
public function GC_Test() { |
15 |
init(); |
16 |
} |
17 |
|
18 |
private function init() : void { |
19 |
num = NUM; |
20 |
stage.addEventListener(MouseEvent.CLICK, clickHandler); |
21 |
while (num--) { |
22 |
var mc : MovieClip = new MovieClip; |
23 |
mc.graphics.beginFill( 0 ); |
24 |
mc.graphics.drawRect( 0 , 0 , 100 , 100 ); |
25 |
mc.x = Math.random() * 500 ; |
26 |
mc.y = Math.random() * 400 ; |
27 |
addChild(mc); |
28 |
} |
29 |
|
30 |
trace (System.totalMemory); |
31 |
} |
32 |
|
33 |
private function clickHandler(e : MouseEvent) : void { |
34 |
clear(); |
35 |
} |
36 |
|
37 |
private function clear() : void { |
38 |
while (numChildren) { |
39 |
removeChildAt( 0 ); |
40 |
} |
41 |
GCPlus.clear( true ); |
42 |
} |
43 |
/*function GC():void{//这是我们熟悉的方法 |
44 |
try{ |
45 |
(new LocalConnection).connect("foo"); |
46 |
(new LocalConnection).connect("foo");}catch(e){ |
47 |
trace(System.totalMemory); |
48 |
} |
49 |
}*/ |
50 |
} |
51 |
} |
通过System.totalMemory的结果可以清楚的看到内存得以释放,window任务管理器也能够看到有变化哦,原理也可能和异常有点关系.
作者:菩提树下的杨过
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。