Perl Language Memory usage optimization Processing long lists

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

If you have a list in memory already, the straightforward and usually sufficient way to process it is a simple foreach loop:

foreach my $item (@items) {
    ...
}

This is fine e.g. for the common case of doing some processing on $item and then writing it out to a file without keeping the data around. However, if you build up some other data structure from the items, a while loop is more memory efficient:

my @result;
while(@items) {
    my $item = shift @items;
    push @result, process_item($item);
}

Unless a reference to $item directly ends up in your result list, items you shifted off the @items array can be freed and the memory reused by the interpreter when you enter the next loop iteration.



Got any Perl Language Question?