加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

为什么在取消分配大数组时,Perl不会垃圾收集内存?

发布时间:2020-12-15 21:12:11 所属栏目:大数据 来源:网络整理
导读:我知道Perl使用基于引用计数的垃圾收集. 当变量超出范围时,引用计数递减,如果REFcount变为0,则内存被取消分配. 但是,当我追踪下面显示的一个小例子时,我无法找到解除分配的情况. print "start.."; sub func{ my $length = 8*1024*1024; my $array = [1..$len
我知道Perl使用基于引用计数的垃圾收集.
当变量超出范围时,引用计数递减,如果REFcount变为0,则内存被取消分配.
但是,当我追踪下面显示的一个小例子时,我无法找到解除分配的情况.
print "start..";
sub func
{
    my $length = 8*1024*1024;
    my $array = [1..$length];
}

func();

print "done..";

在该示例中,当程序启动时,Perl.exe占用大约3 MB的物理内存.
在func()调用中分配后,Perl.exe占用了大约370 MB的内存.
但是在func()调用之后,分配的内存应该被垃圾回收.为什么不做?

期待您的回复.

解决方法

根据 perlfaq3年的“ How can I free an array or hash so my program shrinks?”问题:

You usually can’t. Memory allocated to lexicals (i.e. my() variables)
cannot be reclaimed or reused even if they go out of scope. It is
reserved in case the variables come back into scope. Memory allocated
to global variables can be reused (within your program) by using
undef() and/or delete().

On most operating systems,memory allocated to a program can never be
returned to the system. That’s why long-running programs sometimes re-
exec themselves. Some operating systems (notably,systems that use
mmap(2) for allocating large chunks of memory) can reclaim memory that
is no longer used,but on such systems,perl must be configured and
compiled to use the OS’s malloc,not perl’s.

In general,memory allocation and de-allocation isn’t something you
can or should be worrying about much in Perl.

See also 07002

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读