Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Splitting a string to chunks

by Limbic~Region (Chancellor)
on Nov 29, 2006 at 13:50 UTC ( [id://586699]=note: print w/replies, xml ) Need Help??


in reply to Splitting a string to chunks

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://586699]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (2)
As of 2024-04-20 01:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found