Hello!
2013/10/10 廖宇雷
>
> 我做了一些测试,发现强制 rehash 也不能完全回收 table 占用的空间。
>
你的测试程序本身是有问题的。因为你在初始化 table a 的时候,key 是字符串类型,于是你分配空间的是 table 的 hash
表部分。而你后面强制 rehash 的时候使用的是数值类型的 key,于是只会作用于数组部分的。
> local a = {}
> local limit = 100000
> for i = 1, limit do
> a[tostring(i)] = i
注意你这里使用了 tostring() 进行了 key 的类型转换。去掉这里的 tostring() 调用,便可以实现 rehash
空间释放了。在我这里使用 luajit 运行修改后的版本的输出是
mem 1052.57KB
----------------------------------------
mem 29.64KB
还有一种更简单的做法是直接丢弃原来的 table,让其整体 GC:
local a = {}
local limit = 100000
for i = 1, limit do
a[tostring(i)] = i
end
collectgarbage("collect")
print(string.format("mem %0.2fKB", collectgarbage("count")))
print("----------------------------------------")
a = {}
collectgarbage("collect")
print(string.format("mem %0.2fKB", collectgarbage("count")))
在我这里的输出结果是
mem 5748.67KB
----------------------------------------
mem 283.08KB
Regards,
-agentzh