...
$str .= $1 . $/ while ( $ARGV[0] =~ m/(.{3})/g );
...
####
...
use constant LEN => 3;
...
my $offset = 0;
my $length = LEN;
while ( $_ = substr $ARGV[0], $offset, $length ) {
last if length != LEN;
$str .= $_ . $/;
$offset += $length;
}
...
####
#!usr/bin/perl -w
use strict;
use constant LEN => 3;
use Benchmark qw(:all);
my $str;
my $count = -2;
my $re = timethese(
$count,
{
substring => sub {
my $offset = 0;
my $length = LEN;
while ( $_ = substr $ARGV[0], $offset, $length ) {
last if length != LEN;
$str .= $_ . $/;
$offset += $length;
}
},
regex => sub {
$str .= $1 . $/ while ( $ARGV[0] =~ m/(.{3})/g );
}
}
);
cmpthese($re);
####
Benchmark: running regex, substring for at least 2 CPU seconds...
regex: 1 wallclock secs ( 2.09 usr + 0.00 sys = 2.09 CPU) @ 14030.14/s (n=29323)
substring: 3 wallclock secs ( 2.14 usr + 0.00 sys = 2.14 CPU) @ 23225.70/s (n=49703)
Rate regex substring
regex 14030/s -- -40%
substring 23226/s 66% --
####
...
$str .= $1 . $/ while ( $ARGV[0] =~ m/(.{3})/g ); ## NOTE the number 3
...
####
...
$str .= $1 . $/ while ( $ARGV[0] =~ m/(.{LEN})/g ); ## NOTE 3 is now LEN
...
####
Benchmark: running regex, substring for at least 2 CPU seconds...
regex: 4 wallclock secs ( 2.72 usr + 0.01 sys = 2.73 CPU) @ 740317.95/s (n=2021068)
substring: 2 wallclock secs ( 2.66 usr + 0.02 sys = 2.68 CPU) @ 17332.84/s (n=46452)
Rate substring regex
substring 17333/s -- -98%
regex 740318/s 4171% --