I've used the same idiom, BrowserUK.

One minor nit, however - use a temp variable, and stringify the array before the grep. Stringifying @array2 for each element of @array1 is probably more expensive than building a hash.

Update: Unless I missed something on my benchmark, the faq is the fastest - by far! I didn't expect it, but I should have ;-)

I varied the size of the array and the faq consistently came out on top. The larger @array2 got, the better the faq performed.

#!/usr/bin/perl use strict; use warnings; use Benchmark qw/cmpthese/; use vars qw/@array1 @array2/; sub perlfaq { # lifted from nothingmuch's post above my %hash; $hash{$_} = undef foreach (@array2); @array1 = grep { not exists $hash{$_} } @array1; } sub buk { grep{ local $"="\c1"; -1==index( "\c1@array2\c1", "\c1$_\c1") } @a +rray1; } sub improved { local $" = "\c1"; my $temp = "\c1@array2\c1"; grep { -1==index($temp, "\c1$_\c1") } @array1; } push @array1, int (rand 100) for (1 .. 1000); push @array2, int (rand 100) for (1 .. 100); cmpthese (1_000, { perlfaq => \&perlfaq, buk => \&buk, improved => \&improved, }) __END__ Benchmark: timing 1000 iterations of buk, improved, perlfaq... buk: 58 wallclock secs (50.99 usr + 0.01 sys = 51.00 CPU) @ 19 +.61/s (n=1 000) improved: 4 wallclock secs ( 3.98 usr + 0.00 sys = 3.98 CPU) @ 25 +1.51/s (n= 1000) perlfaq: 1 wallclock secs ( 0.88 usr + 0.00 sys = 0.88 CPU) @ 11 +35.07/s (n =1000) Rate buk improved perlfaq buk 19.6/s -- -92% -98% improved 252/s 1183% -- -78% perlfaq 1135/s 5689% 351% --

In reply to Re: Re: subtract one array from another by jsprat
in thread subtract one array from another by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.