Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Re: adding to the middle of a array

by htoug (Deacon)
on Feb 13, 2003 at 11:33 UTC ( [id://234947]=note: print w/replies, xml ) Need Help??


in reply to Re: adding to the middle of a array
in thread adding to the middle of a array

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.

Replies are listed 'Best First'.
Re: Re: Re: adding to the middle of a array
by TheHobbit (Pilgrim) on Feb 13, 2003 at 11:40 UTC

    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
Re: Re: Re: adding to the middle of a array
by Anonymous Monk on Feb 14, 2003 at 17:56 UTC
    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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (1)
As of 2024-04-25 00:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found