You are right. See the following benchmarks:

use strict; use warnings; use Benchmark 'cmpthese'; sub create { map {rand() < $_[1] ? 1 : 0} 1..$_[0] } sub compare1 { # naive my $x = shift; my $n = shift; return map { my $y=$_; scalar grep { $y->[$_] == 1 and $x->[$_] == 1 + } 0..$n-1 } @_; } sub compare2 { # first find 1s in x, then check in ys my $x = shift; my $n = shift; my @nxs = grep { $x->[$_] } 0..$n-1; return map { my $y=$_; scalar grep { $y->[$_] == 1 } @nxs } @_ ; } sub compare3 { # stringify my $x = shift; $x = join '', @$x; return map { my $j = $x & join'',@$_; $j =~ tr/1/1/ } @_; } my $n = 15000; my $p = 0.005; my $ny = 10; my @x = create $n, $p; my @ys = map { [ create $n, $p ] } 1..$ny; my @r1 = compare1 \@x, $n, @ys; my @r2 = compare2 \@x, $n, @ys; my @r3 = compare3 \@x, @ys; print "compare1: @r1\n"; print "compare2: @r2\n"; print "compare3: @r3\n"; cmpthese( -5, { compare1 => sub{ compare1 \@x, $n, @ys }, compare2 => sub{ compare2 \@x, $n, @ys }, compare3 => sub{ compare3 \@x, @ys }, } );
Results:
Rate compare1 compare3 compare2 compare1 48.8/s -- -81% -91% compare3 253/s 420% -- -53% compare2 537/s 1002% 112% --

In reply to Re^3: Comparing two arrays by hdb
in thread Comparing two arrays by baxy77bax

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.