in reply to adding to the middle of a array

Hi,
Obviously, the one you gave is 'a way' to do it... but there is more than one. The following is the one I use:

my @a = (1,2,3,4,5,6,7,8,9); my $pos = 3; my $new_elem = 100; $" = ", "; print "Before: (@a)\n"; @a = (@a[0..$pos-1],$new_elem,@a[$pos..$#a]); print "After: (@a)\n";

I'm sorry that I haven't the time now to benchmark these solutions...

I hope this serves to help you.

Cheers


Leo TheHobbit

Replies are listed 'Best First'.
Re: Re: adding to the middle of a array
by htoug (Deacon) on Feb 13, 2003 at 11:33 UTC
    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.

      Hi,
      I take the point, and start to read over the camel book as a penance for not having seen how my solution implied a hidden copy...

      Well, ok, reading the Camel Book is not much of a penance, quite the contrary, but WTF... :)

      Cheers


      Leo TheHobbit
      It's very interesting - when I try to increase the iterations to 50000, I see the SPLICE performance drops significant now - Benchmark: timing 50000 iterations of SPLICE... SPLICE: 4 wallclock secs ( 4.28 usr + 0.00 sys = 4.28 CPU) @ 11679.51/s (n=50000) Wonder why it's getting slower...? Daniel