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.

In reply to Re: Filling an array by shagbark
in thread Filling an array by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.