in reply to Re: Optimize code | remove duplicates from AOA.
in thread Optimize code | remove duplicates from AOA.

I doubted that repeated splice on a long array is efficient (because arrays are stored as continuous memory in perl, and splice requires copying the remainder of the array), so wrote a small benchmark:
use 5.010; my @a = map int(10 * rand), 1..1000; sub d_grep { my @copy = @a; @copy = grep { $_ % 2 == 0 } @copy; } sub d_splice { my @copy = @a; my $i = 0; while ($i < @copy) { if ( $copy[$i] % 2 == 1 ) { splice @copy, $i, 1 } else { $i++; } } } use Benchmark qw(cmpthese); cmpthese -2, { grep => \&d_grep, splice => \&d_splice, }; __END__ Rate splice grep splice 2003/s -- -49% grep 3900/s 95% --

I intentionally used in-place edits in both cases, so that the two implementations remain comparable. If you find some flaws in the benchmark, please let me known - writing benchmarks isn't my particular strength :-)

For longer arrays the difference in speed grows.

Perl 6 - links to (nearly) everything that is Perl 6.

Replies are listed 'Best First'.
Re^3: Optimize code | remove duplicates from AOA.
by jethro (Monsignor) on Aug 19, 2010 at 10:39 UTC

    May I answer this with your own words ;-) :

    Ask yourself if your code is actually too slow for your purpose. Only if the answer is "yes", continue.

    Perhaps I should mention that I interpreted his 'efficiency' more in terms of efficient coding than speed (which could be the wrong interpretation)