spurperl,
I was suprised to see that
unpack wasn't the fastest so I changed it just a bit.
my @arr = unpack('A8A8A8A8A8A8A8A8A8A8A8A8A8A8A8A8A8A8A8A8', $str);
Not only is that compatible with older perl's - it is now the fastest. I might play a bit more to see if I can get an even faster version but to be fair, that really should have been:
# No longer wins but is still faster than '(A8)*'
my @arr = unpack((join '', ('A8' x ($strlen / 8))), $str);
Update: I wanted to see what would happen if the benchmark focused more on the functions themselves by removing some of the intermediate calculations. Noticed also I changed x 20 to x 200.
#!/usr/bin/perl
use strict;
use warnings;
use Benchmark 'cmpthese';
my $str = "abcdefgh12345678" x 2000;
my $strlen = length $str;
my $end = $strlen / 8 - 1;
my $fmt = join '', ('A8' x ($strlen / 8));
my @pos = map {$_ * 8} 0 .. $end;
cmpthese(-3, {
'regex' => sub { my @arr = $str =~ /(........)/g;},
'split_grep' => sub { my @arr = grep $_, split /(.{8})/, $str;},
'split_pos' => sub { my @arr = split /(?(?{pos() % 8})(?!))/, $st
+r;},
'substr_map' => sub { my @arr = map substr($str, $_, 8), @pos;},
'substr_for' => sub { my @arr; push @arr, substr($str, $_, 8) for
+@pos;},
'unpack' => sub { my @arr = unpack($fmt, $str);}
});
__DATA__
Rate split_pos split_grep substr_map unpack substr_f
+or
split_pos 38.2/s -- -28% -54% -57% -7
+4%
split_grep 53.1/s 39% -- -36% -41% -6
+4%
regex 77.4/s 110% 52% -- -3% -12%
+ -46%
substr_map 82.3/s 115% 55% -- -8% -4
+5%
unpack 89.5/s 134% 69% 9% -- -4
+0%
substr_for 149/s 291% 182% 81% 67%
+--
-
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.