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% +--

Cheers - L~R


In reply to Re: Splitting a string to chunks by Limbic~Region
in thread Splitting a string to chunks by spurperl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.