Don't use $&, it will slow down every regular expression in the program
You're quite right, Sir ;-)
#!/usr/bin/perl -w
use Benchmark;
my $string = "CCATGNNNTAACCNNATGNNTAGCC" x 10000;
timethese(10, {
'matchamp' => sub {matchamp($string)},
'matchpar' => sub {matchpar($string)},
});
sub matchamp {
my $string = shift;
my $matchlen = 0;
while($string =~ /[AG]TG.*?[AG][AG]/g) {
$matchlen += length($&); # Actually reference $& to keep Perl from
+ cheating
}
return $matchlen;
}
sub matchpar {
my $string = shift;
my $matchlen = 0;
while ( $string =~ /([AG]TG.*?T[AG][AG])/g ) {
$matchlen += length($1); # Reference $1, for fairness
}
return $matchlen;
}
yields:
Benchmark: timing 10 iterations of matchamp, matchpar...
matchamp: 24 wallclock secs (23.48 usr + 0.00 sys = 23.48 CPU) @ 0
+.43/s (n=10)
matchpar: 26 wallclock secs (25.70 usr + 0.00 sys = 25.70 CPU) @ 0
+.39/s (n=10)
The "$&" leg seems a tad faster, right?
BUT...
removing every trace of matchamp in the above program yields:
Benchmark: timing 10 iterations of matchpar...
matchpar: 1 wallclock secs ( 0.54 usr + 0.00 sys = 0.54 CPU) @ 18
+.52/s (n=10)
That's a speedup by a factor ~26. I'm impressed.
Thanks for pointing that out
-
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.