If his quickly means faster, let's compare those two solutions:

use Benchmark qw(timethese); use strict; use warnings; my @array = (1 .. 100000); timethese(100, {granfather => \&grandfather, usual => \&usual}); sub grandfather { return 1 if grep {$_ == 100000} @array; } sub usual { for my $a (@array) { return 1 if ($a == 100000); } return 0; }

If the element we serach is at the end, grandfather's is a little bit faster:

Benchmark: timing 100 iterations of granfather, usual... granfather: 4 wallclock secs ( 3.58 usr + 0.00 sys = 3.58 CPU) @ 27 +.95/s (n=1 00) usual: 4 wallclock secs ( 4.13 usr + 0.00 sys = 4.13 CPU) @ 24 +.24/s (n=1 00)

But if you change the above code to search for 3 (at the beginning of the array), then the usual way is much faster:

Benchmark: timing 100 iterations of granfather, usual... granfather: 3 wallclock secs ( 3.58 usr + 0.00 sys = 3.58 CPU) @ 27 +.95/s (n=1 00) usual: 0 wallclock secs ( 0.00 usr + 0.00 sys = 0.00 CPU) (warning: too few iterations for a reliable count)

With something in the middle say 50000, the usual way is still close to 50% faster.

Benchmark: timing 100 iterations of granfather, usual... granfather: 4 wallclock secs ( 3.69 usr + 0.03 sys = 3.72 CPU) @ 26 +.89/s (n=1 00) usual: 2 wallclock secs ( 2.08 usr + 0.00 sys = 2.08 CPU) @ 48 +.12/s (n=1 00)

Now you know which direction it is pointing to ;-)


In reply to Re^2: how to quickly tell if number is in an array by pg
in thread how to quickly tell if number is in an array by redss

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.