Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Perl and Garbage Collection

by Svetlana (Novice)
on Oct 01, 2016 at 13:44 UTC ( [id://1173079]=perlquestion: print w/replies, xml ) Need Help??

Svetlana has asked for the wisdom of the Perl Monks concerning the following question:

How well does Perl do garbage collection?

What I mean is, in a language like C#/Java, GC is taken care of pretty well, to the point that the programmer rarely(I do mean rare!) has to call the GC themselves. You'd have to be really careless in Java to have a memory leak, more so in C#.

I don't know all that much, but in C++ I've read the programmer has to be aware of and take care of memory leaks themselves. Do perl programmers have to worry like C++ programmers do?

Replies are listed 'Best First'.
Re: Perl and Garbage Collection
by BrowserUk (Patriarch) on Oct 01, 2016 at 14:16 UTC

    Perl doesn't use garbage collection per se, but rather reference counting.

    Which basically means that memory is handed back to the memory pool, once it is no longer referenced. Automatically.

    In this snippet:

    sub fred { my( $x, $y ) = @_; my $result = $x * $y; return $result; }

    When the sub returns, none of the variables inside it can be referenced from anywhere else, so their reference counts are zero, and their memory will be returned to the pool, as the subroutine ends.

    In this snippet:

    sub genList { my( $start, $end, $step ) = @_; my @list; for( my $i=$start; $i < $end; $i += $step } push @list, $i; return \@list; } ... if( ??? ) { my $arrayRef = getList( 10, 99, 3 ); ## use list }

    The contents of array @list persists beyond the life of genList(), because the array is returned by reference; thus its reference count has been incremented, and is non-zero when genList() ends.

    However, when the calling if block ends, that reference count will be decremented, and as it will drop to zero, the memory will be freed back to pool.

    Bottom line: for the most part, Perl programmer's do not worry about, or suffer from, memory leaks. Nor does their code suffer those awful pregnant pauses whilst the garbage collector goes off searching through memory trying to find and clean up no longer used space. Memory is reclaimed automatically, on the fly, as soon as it is no longer needed.

    It is possible to create memory leaks, by creating self-referencing structures, but you have to work hard to do it, and there are techniques -- weakening -- to deal with it if, the self-referential data is a deliberate need, rather than accidental. In 15 years of daily Perl, including a lot of very heavy data processing, I've never needed to use weakening.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Perl and Garbage Collection
by haukex (Archbishop) on Oct 01, 2016 at 14:13 UTC

    Hi Svetlana,

    Do perl programmers have to worry like C++ programmers do?

    In general, no. The main thing to remember is that circular references will prevent garbage collection. Other than that, Perl programmers don't usually have to worry about memory management, exceptions may be when trying to fit large amounts of data into RAM, or when writing XS code.

    I think you'll find the replies in this thread very informative: Do subroutine variables get destroyed?

    Hope this helps,
    -- Hauke D

Re: Perl and Garbage Collection
by eyepopslikeamosquito (Archbishop) on Oct 02, 2016 at 07:27 UTC
Re: Perl and Garbage Collection
by ikegami (Patriarch) on Oct 03, 2016 at 20:22 UTC

    Perl's uses reference counting as its method of doing garbage collection. As soon as the last reference to a value is released, the value is destroyed and freed. This has both advantages and disadvantages over Java's approach.

    A disadvantage over Java's method is that you have to worry about circular references which will cause a leak.

    push @{ $parent->{children} }, $child; weaken( $child->{parent} = $parent ); # Needed to avoid memory leak.

    An advantage over Java's method is that you don't have to worry about when the object is destroyed, as it will be destroyed the moment is ceases being referenced. This avoids subtle, intermittent, timing-dependent errors.

    { Resource res = get_resource_exclusively(res_id); // ... res.release(); // Needed or the next line might fail. } { Resource res = get_resource_exclusively(res_id); // ... res.release(); }

    You might even need a try/catch block to ensure timely destruction in some places.

    Resource res = get_resource_exclusively(res_id); try { // ... } catch (Exception e) { res.release(); throw e; }
Re: Perl and Garbage Collection
by andal (Hermit) on Oct 04, 2016 at 07:44 UTC

    The GC of Perl does very good work, it collects all variables that it is supposed to :) But each GC has its limitations. Otherwise, there would be no need in things like "weak references". They are available in Java, C#, Perl and few other languages.

    Creating memory leak in Java is very easy. Just add event listener while building GUI, and then discard it without unregistering. GC is convenient, but it does not mean, that programmer should not think about memory management. That thing is unavoidable. So, just like in any other programming language, one has to know about peculiarities of GC in Perl, and then manage memory appropriately.

    On a side note, I believe C is the best language for development. Simply because it does not pretend, that one should not worry about memory management :)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1173079]
Front-paged by Arunbear
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-19 16:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found