perl - 为什么在释放大数组时 Perl 不垃圾回收内存?

标签 perl memory-management

我知道 Perl 使用基于引用计数的垃圾收集。
当变量超出范围时,引用计数递减,如果 REFcount 变为 0,则取消分配内存。
但是当我跟踪如下所示的一个小例子时,我无法找到正在发生的取消分配。

print "start..";

memory usage at start state
sub func
{
    my $length = 8*1024*1024;
    my $array = [1..$length];

memory usage after allocation
}

func();

print "done..";

memory usage during garbage collection stage

在示例中,当程序启动时,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.

See also How can I make my Perl program take less memory?

关于perl - 为什么在释放大数组时 Perl 不垃圾回收内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14159258/

相关文章:

perl - 我想访问子程序外部的私有(private)变量

iphone - UIImagePicker 的内存问题

c++ - 当传递 [] 数组但不传递来自 malloc 的内存时,该方法有效

c++ - 为什么我得到 "Invalid Allocation Size: 4294967295 Bytes"而不是 std::bad_alloc 异常?

eclipse - 如何使 Eclipse 与 `perlbrew` 一起工作?

mysql - 在 @INC 中找不到 Email/MIME.pm

perl - 在使用 ("XXX"时不能使用字符串 "strict refs") 作为符号引用

regex - 用正则表达式匹配一个字符串

c++ - 删除基于堆的对象后,STL 容器会释放内存吗?

linux - 内存在 32 位系统中未使用?