processing strings char-by-char

Discussion in 'Perl Misc' started by Rainer Weikusat, Aug 18, 2013.

  1. 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);
    }});
     
    Rainer Weikusat, Aug 18, 2013
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. pmatos
    Replies:
    3
    Views:
    411
    Andrew Koenig
    Mar 7, 2005
  2. John Devereux

    Should I use "char" or "unsigned char" for strings?

    John Devereux, Mar 28, 2005, in forum: C Programming
    Replies:
    4
    Views:
    650
    Eric Sosman
    Mar 29, 2005
  3. lovecreatesbeauty
    Replies:
    1
    Views:
    1,149
    Ian Collins
    May 9, 2006
  4. Ben

    Strings, Strings and Damned Strings

    Ben, Jun 22, 2006, in forum: C Programming
    Replies:
    14
    Views:
    810
    Malcolm
    Jun 24, 2006
  5. Rainer Weikusat

    processing strings char-by-char

    Rainer Weikusat, Aug 18, 2013, in forum: Perl Misc
    Replies:
    3
    Views:
    174
    John W. Krahn
    Aug 20, 2013
Loading...

Share This Page