processing strings char-by-char

R

Rainer Weikusat

So far, I came up with three obvious ways to do that:

$r ^= ord($1) while $string =~ /\G(.)/g;

This extracts successive characters from the string with a 'moving
regex match'.

$r ^= ord($_) for split(//, $string);

This splits the string into a list of characters and loops over that.

$r ^= ord(substr($string, $_, 1)) for 0 .. length($string);

This loops over the 'character positions' in $string and uses substr
to extract the corresponding characters.

When benchmarking these three, the one I like best (the regex match)
comes out slowest. The 'split string, loop over list' method is about
twice as fast as the regex and the most clumsy one (IMHO), substr,
runs at about 1.5 times the speed of the split loop.

-----------------
use Benchmark;

my $string = 'A' x 100;

timethese(-3,
{
while => sub {
my $r;
$r ^= ord($1) while $string =~ /\G(.)/g;
},

for => sub {
my $r;
$r ^= ord($_) for split(//, $string);
},

substr => sub {
my $r;
$r ^= ord(substr($string, $_, 1)) for 0 .. length($string);
}});
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top