It's a tradeoff. As the OP noted, if you increase the range of squares you're checking, precomputing gets slower (and it's time you don't count in your benchmark). Stick another 0 on MAX_NUMBER and run your bench again (change the first arg for cmpthese to -10), and you might get something like I did:
Rate Regexp Index Sqrt
Regexp 3.82/s -- -88% -98%
Index 32.4/s 748% -- -81%
Sqrt 167/s 4281% 417% --
One relatively easy optimization that I didn't do is to limit the length to what can actually be matched:
sub m_sqrt {
my $total_length;
my %seen;
my $max_length = length($MAX_NUMBER * $MAX_NUMBER);
for my $start (0..length $string) {
next if substr($string, $start, 1) eq '0';
my $this_max = length($string)-$start;
$this_max = $max_length if $max_length < $this_max;
for my $length (1..$this_max) {
my $test = substr($string, $start, $length);
my $sqrt = sqrt($test);
if (!$seen{$test}++ and $sqrt == int $sqrt
and $sqrt >= $MIN_NUMBER and $sqrt <= $MAX_NUMBER)
+ {
$total_length += $length;
}
}
}
return ($total_length);
}
Now the bench gives me
Rate Regexp Index Sqrt
Regexp 3.64/s -- -88% -99%
Index 31.2/s 758% -- -94%
Sqrt 497/s 13542% 1489% --
Caution: Contents may have been coded under pressure.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.