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

前端之家收集整理的这篇文章主要介绍了为什么在取消分配大数组时,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

猜你在找的Perl相关文章