Lesson to be learned from this: Use the builtins.

You method will copy the entire @a array back and forth, while the builtin splice will do as little work as possible (and probably will add to the array by shuffling around with pointers instead of copying the contents).

A simple benchmark:

use Benchmark "timethese"; my @c = (1,2,3,4,5,6,7,8,9); my @s = (1,2,3,4,5,6,7,8,9); my $pos = 3; my $new_elem = 100; timethese(5000, { COPY => sub {@c = (@c[0..$pos-1],$new_elem,@c[$pos..$#c])}, SPLICE=> sub {splice (@s, $pos, 0, $new_elem)}, }); print "\nAfter iters: size(\@copy): ", scalar @c, " and size(\@splice) +: ", scalar(@s), "\n";
will show that:
Benchmark: timing 5000 iterations of COPY, SPLICE...
      COPY: 12 wallclock secs (11.88 usr +  0.00 sys = 11.88 CPU) @ 420.76/s (n=5000)
    SPLICE:  0 wallclock secs ( 0.05 usr +  0.00 sys =  0.05 CPU) @ 100000.00/s (n=5000)
            (warning: too few iterations for a reliable count)

After iters: size(@copy): 5009 and size(@splice): 5009
The COPY times get worse and worse, while SPLICE has to get up to 50000 iterations before it takes even 6 wallclock seconds.

In reply to Re: Re: adding to the middle of a array by htoug
in thread adding to the middle of a array by stu96art

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.