What is the best way to delete a value from an array in Perl?

前端 未结 14 2384
忘掉有多难
忘掉有多难 2020-12-12 20:17

The array has lots of data and I need to delete two elements.

Below is the code snippet I am using,

my @array = (1,2,3,4,5,5,6,5,4,9);
my $element_o         


        
14条回答
  •  南方客
    南方客 (楼主)
    2020-12-12 21:03

    Just to be sure I have benchmarked grep and map solutions, first searching for indexes of matched elements (those to remove) and then directly removing the elements by grep without searching for the indexes. I appears that the first solution proposed by Sam when asking his question was already the fastest.

        use Benchmark;
        my @A=qw(A B C A D E A F G H A I J K L A M N);
        my @M1; my @G; my @M2;
        my @Ashrunk;
        timethese( 1000000, {
          'map1' => sub {
              my $i=0;
              @M1 = map { $i++; $_ eq 'A' ? $i-1 : ();} @A;
          },
          'map2' => sub {
              my $i=0;
              @M2 = map { $A[$_] eq 'A' ? $_ : () ;} 0..$#A;
          },
          'grep' => sub {
              @G = grep { $A[$_] eq 'A' } 0..$#A;
          },
          'grem' => sub {
              @Ashrunk = grep { $_ ne 'A' } @A;
          },
        });
    

    The result is:

    Benchmark: timing 1000000 iterations of grem, grep, map1, map2...
      grem:  4 wallclock secs ( 3.37 usr +  0.00 sys =  3.37 CPU) @ 296823.98/s (n=1000000)
      grep:  3 wallclock secs ( 2.95 usr +  0.00 sys =  2.95 CPU) @ 339213.03/s (n=1000000)
      map1:  4 wallclock secs ( 4.01 usr +  0.00 sys =  4.01 CPU) @ 249438.76/s (n=1000000)
      map2:  2 wallclock secs ( 3.67 usr +  0.00 sys =  3.67 CPU) @ 272702.48/s (n=1000000)
    M1 = 0 3 6 10 15
    M2 = 0 3 6 10 15
    G = 0 3 6 10 15
    Ashrunk = B C D E F G H I J K L M N
    

    As shown by elapsed times, it's useless to try to implement a remove function using either grep or map defined indexes. Just grep-remove directly.

    Before testing I was thinking "map1" would be the most efficient... I should more often rely on Benchmark I guess. ;-)

提交回复
热议问题