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 ;-)
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.