我知道 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() 调用之后,分配的内存应该被垃圾回收。为什么没有完成?
期待您的回复。
最佳答案
根据How can I free an array or hash so my program shrinks?中的问题“perlfaq3” :
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.
关于perl - 为什么在释放大数组时 Perl 不垃圾回收内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14159258/