微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我知道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

原文地址:https://www.jb51.cc/Perl/172584.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐