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% --
With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|