For some cases, it will be faster to not move all of the elements down each time:
- tyemy $o= 0; for my $i ( 0..$#$av ) { if( should_keep($i) ) { $av->[$o++]= $av->[$i]; } } $#$av= $o-1;
#!/usr/bin/perl -w use strict; my @prime= qw( 1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 ); my %prime; @prime{@prime}= (1)x@prime; sub one { my $av= [ 0..100 ]; my $o= 0; for my $i ( 0..$#$av ) { if( $prime{$i} ) { $av->[$o++]= $av->[$i]; } } $#$av= $o-1; return $av; } sub for { my $av= [ 0..100 ]; for my $i ( reverse 0 .. $#$av ) { splice( @$av, $i, 1 ) if ! $prime{$i}; } return $av; } sub whl { my $av= [ 0..100 ]; my $i= @$av; while( 0 <= --$i ) { splice( @$av, $i, 1 ) if ! $prime{$i}; } return $av; } printf "(%s)\n", join " ", @{&one()}; printf "(%s)\n", join " ", @{&for()}; printf "(%s)\n", join " ", @{&whl()}; use Benchmark qw( cmpthese ); cmpthese( -3, { one => \&one, for => \&for, whl => \&whl, } ); __END__ Rate whl for one whl 2610/s -- -63% -78% for 7049/s 170% -- -41% one 11986/s 359% 70% --
In reply to (tye)Re: What's the idiom for finding and removing the found @ARRAY element?
by tye
in thread What's the idiom for finding and removing the found @ARRAY element?
by John M. Dlugosz
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |