I was curious how using map and multiplication to generate the slice, without any conditionals, would compare. ("mult" in this example.) Interestingly, map is killing grep on my machine, which differs from what GrandFather got.

#/usr/bin/perl use warnings; use strict; use Benchmark qw(cmpthese); my @arr = (0,3,4,5,8,10,12,15, 1..999999); cmpthese (-2, { mapgrep => sub {map {$arr[$_]} grep {$_ & 1} 1..$#arr}, slice => sub {@arr[ grep {$_ & 1} 1..$#arr ];}, mult => sub {@arr[map {$_*2+1} 0..int(@arr/2)-1];}, grep => sub {my $ind = 0; grep {$ind++ % 2} @arr}, push => sub {my @var; push(@var, $arr[$_*2+1]) for 0..int(@arr +/2)-1}, map => sub {map { $arr[$_*2+1] } 0..int(@arr/2)-1}, } );

This is a multiprocessor x86-64 machine, for what it's worth.

~/perl$ cat /proc/version Linux version 2.6.26.8-57.fc8 (mockbuild@x86-4.fedora.phx.redhat.com) +(gcc version 4.1.2 20070925 (Red Hat 4.1.2-33)) #1 SMP Thu Dec 18 18: +59:49 EST 2008 ~/perl$ perl -v This is perl, v5.8.8 built for x86_64-linux-thread-multi ~/perl$ perl ./everyother.pl Rate mapgrep slice push mult grep map mapgrep 5.24/s -- -22% -28% -33% -34% -43% slice 6.73/s 28% -- -8% -14% -15% -27% push 7.28/s 39% 8% -- -7% -8% -21% mult 7.80/s 49% 16% 7% -- -1% -15% grep 7.92/s 51% 18% 9% 1% -- -14% map 9.22/s 76% 37% 27% 18% 16% --

Update: As an added note, ($_<<1)+1 is slightly faster still, but doesn't catch up to the map and grep solutions.


In reply to Re^3: Quicly extracting odd index elements in the array with grep by ssandv
in thread Quicly extracting odd index elements in the array with grep 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.