Quick thought to reduce capturing: m|()A|gs?
Unfortunately it seems the extra capture group actually slows things down - no matter how much I fiddle with the parameters at the top, nocapt is always about 2x as fast:
#!/usr/bin/env perl
use warnings;
use strict;
use Benchmark qw/cmpthese/;
my $count = 1000;
my $match = 'ABC'x20;
my $space = 'xAz'x100;
my $str = ( $space.$match x $count ) . $space;
cmpthese(-3, {
nocapt => sub {
die unless $count == ( () = $str =~ m|\Q$match|gs );
},
withcapt => sub {
die unless $count == ( () = $str =~ m|()\Q$match|gs );
},
});
__END__
Rate withcapt nocapt
withcapt 4264/s -- -50%
nocapt 8596/s 102% --