2006-12-17 12:11 ActionScript 3.0 - Function Closure GC Bug
ActionScript 3.0 - Function Closure GC Bug
依照文件上的定義
ActionScript 3.0 function closure 是一個物件,包含一個函式與詞彙環境的快照
函式的詞彙環境包含函式範圍鏈內所有的變數、屬性、方法、物件....
既然是一個物件,應該是可以被回收的
以下是一個測試程式
每 1 ms 執行一次函式 (已經測試過了,不用擔心電腦會當掉啦)
產生一個 function closure 物件並編上流水號
存到弱引用 (weak reference) 的 Dictionary 集合內
並且計算 Dictionary 內 key 的數量
假如 key 數量小於 4 ( 避免 trace 太多訊息出來)
列出所有的 function closure 編號
package {
import flash.display.*;
import flash.events.*;
import flash.utils.*;
import flash.system.System;
public class FunctionClosure extends Sprite {
public var dict:Dictionary = new Dictionary(true);
public static var index:Number = 0;
public static function getFun():Function{
var fun:Function = function():void{
trace("anonymous function");
};
fun.prototype.index = index++;
return fun;
}
public function countDict():Number{
var count:Number = 0;
for(var i:Object in dict) {
count++;
}
return count;
}
public function doTest():void{
var dictCount:Number = countDict();
if (dictCount < 4) {
trace("count : " + dictCount + "\t totalMemory : " + System.totalMemory);
for(var i:Object in dict) {
trace("index : " + i.prototype.index);
}
}
var fun:Function = getFun();
dict[fun] = null;
}
public function FunctionClosure() {
// 決定是否用第一個 function closure 當作 Listener
// var fun:Function = getFun();
setInterval(doTest, 1);
}
}
}
測試結果可以發現到
每隔一段時間
function closure 就會被回收一次
但是編號為 0 的 function closure 一直都存在 Dictionary 集合內
始終都不會消失
這意味著『第一次產生的 function closure 無法被回收』
可以算是蠻嚴重的 Bug 了吧
將 function closure 改由 package function 產生
或是改成 static function 產生
也都是一樣
相關資料:
ActionScript 3.0 - Function Closure
Scope Chain and Memory waste in Flash MX
回應

