in reply to foreach array - delete current row ?
Three methods; which is best depends upon the size of the array, but grep is never a bad choice unless you're tight on memory:
#! perl -slw use strict; use Benchmark qw[ cmpthese ]; our $N //= 1e3; cmpthese -1, { for_splice => q[ my @a = 1 .. $N; $a[$_] =~ /9/ and splice @a, $_, 1 for reverse 0 .. $#a; ], grep => q[ my @a = 1 .. $N; @a = grep !/9/, @a; ], offset_copy => q[ my @a = 1 .. $N; my $o = 0; for( 0 .. $#a ) { $a[$_-$o] = $a[$_]; $a[ $_ ] =~ /9/ and ++$o; } $#a = $#a - $o; ], }; __END__ C:\test>1036622 -N=1e2 Rate grep offset_copy for_splice grep 8144/s -- -14% -19% offset_copy 9489/s 17% -- -5% for_splice 10035/s 23% 6% -- C:\test>1036622 -N=1e3 Rate grep offset_copy for_splice grep 732/s -- -19% -44% offset_copy 898/s 23% -- -31% for_splice 1304/s 78% 45% -- C:\test>1036622 -N=1e4 Rate for_splice grep offset_copy for_splice 64.9/s -- -9% -33% grep 71.6/s 10% -- -27% offset_copy 97.5/s 50% 36% -- C:\test>1036622 -N=1e5 (warning: too few iterations for a reliable count) Rate for_splice grep offset_copy for_splice 1.56/s -- -78% -80% grep 7.00/s 348% -- -13% offset_copy 8.00/s 412% 14% -- C:\test>1036622 -N=1e6 (warning: too few iterations for a reliable count) (warning: too few iterations for a reliable count) (warning: too few iterations for a reliable count) s/iter for_splice grep offset_copy for_splice 71.8 -- -98% -98% grep 1.36 5183% -- -20% offset_copy 1.09 6467% 24% --
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: foreach array - delete current row ?
by roboticus (Chancellor) on Jun 03, 2013 at 10:50 UTC | |
by BrowserUk (Patriarch) on Jun 03, 2013 at 13:44 UTC | |
by roboticus (Chancellor) on Jun 03, 2013 at 18:05 UTC | |
by Anonymous Monk on Apr 27, 2015 at 01:55 UTC | |
by BrowserUk (Patriarch) on Apr 27, 2015 at 08:24 UTC |