Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Management in perl

I have facing a weird issue of handling memory in perl. I am working in a perl application which uses pretty big hash-structures. I am assigning the has ref to and fro objects. But at the end it seems even if I am deallocating the object and the hash, the memory usage is remaining same.

Here is a sample of the problem:

 my $hash = {};
 .............
 this ds gets populated with a lot of data ...
 .......
 {
      my $obj = new Class("data"=>$hash);
 .......
 .......
 ......

 }

 #even undefing the $hash
 undef $hash;

 # I can expect some improvement in Memory Utilization, but its not happening

I think I am doing some very basic mistakes. Can any one suggest?

like image 282
Kallol Avatar asked Sep 27 '12 10:09

Kallol


2 Answers

You can't really return memory back to the OS. Perl will usually keep it in order to reallocate it later, though it will garbage collect occasionally.

See http://learn.perl.org/faq/perlfaq3.html#How-can-I-free-an-array-or-hash-so-my-program-shrinks-

and

http://clokwork.net/2012/02/12/memory-management-in-perl/

like image 158
Joshua Allen Avatar answered Oct 13 '22 00:10

Joshua Allen


Generally speaking, Perl memory management does what you need to do, and you needn't worry about it. For example, what is the harm of keeping a huge chunk of memory allocated for the rest of your program? Probably none. Perl will release it if your OS is in danger of running out of memory.

Suppose you had some special case, like a script that runs constantly in the background, but occasionally needs to do a memory-intensive task. You could solve this by separating it into two scripts: background.pl and the memory-intensive-task.pl. The background.pl would execute memory-intensive-task.pl when needed. The memory would be freed when this program completed and exited.

like image 23
dan1111 Avatar answered Oct 13 '22 01:10

dan1111