in reply to Re: What's the idiom for finding and removing the found @ARRAY element?
in thread What's the idiom for finding and removing the found @ARRAY element?

For some cases, it will be faster to not move all of the elements down each time:

my $o= 0; for my $i ( 0..$#$av ) { if( should_keep($i) ) { $av->[$o++]= $av->[$i]; } } $#$av= $o-1;

        - tye
#!/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% --

Replies are listed 'Best First'.
Re: (tye)Re: What's the idiom for finding and removing the found @ARRAY element?
by jdporter (Paladin) on Nov 06, 2002 at 16:53 UTC
    As far as that goes, it might be more efficient, in some cases, to not change the length of the array at all, and just set the "undesirable" elements to undef. Then, later, when the array is processed, just skip over the undef ones.