in reply to Re: adding to the middle of a array
in thread adding to the middle of a array
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:
will show that: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";
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 | |
|
Re: Re: Re: adding to the middle of a array
by Anonymous Monk on Feb 14, 2003 at 17:56 UTC |