Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Filling an array

by shagbark (Acolyte)
on Mar 21, 2018 at 14:20 UTC ( [id://1211423]=note: print w/replies, xml ) Need Help??


in reply to Filling an array

File time-array-init.pl tests how long each method of initializing and filling an array takes:
use Time::HiRes qw(gettimeofday); use strict; use warnings; sub timeSub { my ($sub, @parms) = @_; my ($sec0, $micro0)=gettimeofday; my $name = $sub->(1000000, @parms); my ($sec1, $micro1)=gettimeofday; my $diff = 1000000*($sec1-$sec0) + $micro1-$micro0; print "$name:\t$diff microseconds\n"; } sub pushInit { my $loops = shift; my @x; for (my $i=0; $i<$loops; $i++) { push(@x, 1) } return "push"; } sub elInit { my $loops = shift; my @x; for (my $i=0; $i<$loops; $i++) { $x[$i] = 1 } return "\$a[\$i]"; } sub xInit { my $loops = shift; my @x = (1) x $loops; return "(1) x"; } # This method builds the array (1, 2, 3, ...), not (1, 1, 1, ...) sub dotInit { my $loops = shift; my @x = 1..$loops; return ".."; } foreach my $subR (\&pushInit, \&elInit, \&xInit, \&dotInit) { &timeSub($subR); }
Running it:
$ perl time-array-init.pl push: 171028 microseconds $a[$i]: 163881 microseconds (1) x: 51077 microseconds ..: 70115 microseconds
I would guess that the first 2 methods also consume a lot more memory, as Perl 5 isn't good at reclaiming memory from deleted objects.

Replies are listed 'Best First'.
Re^2: Filling an array
by hippo (Bishop) on Mar 21, 2018 at 15:11 UTC
    Perl 5 isn't good at reclaiming memory from deleted objects.

    What grounds do you have for this assertion, please?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1211423]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2024-04-24 13:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found