Wow, I totally should have seen that!
Okay so now that mutual correctness has been established, it is time for optimality checking. It turns out that your method is about 10% faster.
I called my method
unroll, and your method
rollahead.
Here are the benchtests:
Benchmark: timing 100000 iterations of rollahead, unroll...
rollahead: 18.3956 wallclock secs (17.94 usr + 0.00 sys = 17.94 CPU) @ 5575.07/s (n=100000)
unroll: 22.1357 wallclock secs (20.58 usr + 0.00 sys = 20.58 CPU) @ 4859.56/s (n=100000)
Rate unroll rollahead
unroll 4860/s -- -13%
rollahead 5575/s 15% --
and the code:
use strict;
use Benchmark ':all', ':hireswallclock';
my $x = "#@##@###@####@#####@";
my $y = reverse $x;
my $z = "$x$x$x$y$y$x$x$y$y$y$y$y$x$x$x$x";
my $r = timethese(
100000,
{
unroll => sub {
my @x = ([unroll($x)],[unroll($y)],[unroll($z)])
},
rollahead => sub {
my @x = ([rollahead($x)],[rollahead($y)],[rollahead($z)])
},
}
);
cmpthese($r);
sub unroll {
my @x = $_[0] =~ /(?:^|@)((?:##|#@|[^#@])*)/g;
for(@x){
$_ =~ s/##/#/g;
$_ =~ s/#@/@/g;
} @x
}
sub rollahead {
my $x = shift;
$x = reverse $x;
my @x = reverse(split/\@(?=(?:##)*(?!#))/,$x,-1);
for(@x){
$_ = reverse;
$_ =~ s/##/#/g;
$_ =~ s/#@/@/g;
} @x
}
Is there a monk who could explain why
rollahead is faster? I was surprised considering the number of calls to reverse. I can only guess that somewhere deep inside the guts of the Perl-Regex-Beasty, that the optimizer droids are nasty hardcore with lookaround automata but can't be bothered with alternation.
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.