If you need to generate the intersection between your array1 and another array more than once, then there is a way of speeding this process up by a huge factor (over 10000%!) relative to using the FAQ intersection method.
Instead of generating a new hash from array's 1 & 2 each time you need to do this, you can use a %hash1 in place of @array1. In use, you would need to swap your array1 references from $array1[n] to $aryHash1{n};, you wouldn't be able to have duplicates in aryHash1, and it would use additional memory, but less than the combined space of an array and a temporary hash for doing the intersection.
Benchmark
#! perl -sw use strict; use Benchmark::Timer; my $timer = Benchmark::Timer->new(skip => 1); local $\=$/; sub intersect (\@\@) { my ($aryRef1, $aryRef2) = @_; my %count = (); $count{$_}++ foreach @$aryRef1, @$aryRef2; return grep{ $count{$_} == 1 } keys %count; } my @aryBase = (1 .. 28000); my %hashBase; @hashBase{@aryBase} = undef; my @array2 = (1..1000, 1..100); # create some duplicates with duplicat +es for (0..100){ my @array1 = @aryBase; $timer->start('faq'); my @dup = intersect( @array1, @array2 ); $timer->stop('faq'); } for (0..100){ my %hashAry = %hashBase; $timer->start('delete'); my @dup = delete @hashAry{@array2}; $timer->stop('delete'); } $timer->report; @aryBase = intersect( @aryBase, @array2 ); print '\@aryBase contains ', scalar @aryBase, ' elements after interse +ct'; delete @hashBase{@array2}; print '\@hashBase contains ', scalar keys %hashBase, ' elements after +intersect'; __END__ #output C:\test>207632 100 trials of faq (103.692s total), 1.037s/trial 100 trials of delete (881.000ms total), 8.810ms/trial \@aryBase contains 27000 elements after intersect \@hashBase contains 27000 elements after intersect C:\test>
By my calculation, this is an 1037/8.81*100 = 11770% faster! Did I make a mistake?
In reply to Re: How to splice out multiple entries from an array
by BrowserUk
in thread How to splice out multiple entries from an array
by Ya
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |