in reply to Re: Optimize code | remove duplicates from AOA.
in thread Optimize code | remove duplicates from AOA.
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Optimize code | remove duplicates from AOA.
by jethro (Monsignor) on Aug 19, 2010 at 10:39 UTC |