Borrowing heavily from Kenosis' code (thanks), regex seems to be faster than unpack (at least using substitution):
Rate _substr _unpack _regex _split
_substr 2187335/s -- -11% -16% -20%
_unpack 2457294/s 12% -- -6% -10%
_regex 2612321/s 19% 6% -- -4%
_split 2726283/s 25% 11% 4% --
Perl code:
use strict;
use warnings;
use Benchmark qw/cmpthese/;
my $string = join '', 'A' .. 'Y';
sub _unpack {
my @arr = unpack '(A5)*', $string;
}
sub _regex {
my @arr;
while (length $string){ $string =~ s/^(.{5})//; push @arr, $1; }
}
sub _split {
my @arr = split /.{5}\K/, $string;
}
sub _substr {
my @arr;
for ( my $i = 0 ; $i < length $string ; $i += 5 ) {
push @arr, substr $string, $i, 5;
}
}
cmpthese(
-5,
{
_unpack => sub { _unpack() },
_split => sub { _split() },
_substr => sub { _substr() },
_regex => sub { _regex() }
}
);
-
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.