Precompiling regexes can make a dramatic difference. Compare the stats below for u1 vs u5 -- there's an 868% speedup on my box!
Nevertheless, the backreference is just a better algo, and it still wins.
use Benchmark qw( cmpthese ) ;
my $digits = 2491306578;
my @regexes = map { qr/$_/ } 0 .. 9;
cmpthese( -5, {
u1 => sub{
for ( 0 .. 9 ) {
return 0 if $digits !~ /$_/;
}
return 1;
},
u2 => sub{
my @x = sort split //, $digits;
my $x = join "", @x;
$x =~ tr/0-9//s;
length $x == 10 ? return 1 : return 0;
},
u3 => sub {
return 0 if $digits =~ /(\d).*\1/; return 1;
},
u4 => sub {
return $digits !~ /(.).*\1/;
},
u5 => sub {
for (@regexes) {
return 0 if $digits !~ $_;
}
return 1;
}
Rate u1 u2 u5 u3 u4
u1 10555/s -- -71% -90% -93% -93%
u2 35955/s 241% -- -65% -76% -76%
u5 102215/s 868% 184% -- -32% -32%
u3 149240/s 1314% 315% 46% -- -1%
u4 150091/s 1322% 317% 47% 1% --
-
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.
|