[Israel.pm] count chars

Ephraim Dan E.Dan at F5.com
Mon Sep 3 04:33:11 PDT 2007


use Benchmark;

My first thought would be to use index() instead of a regexp, and it indeed proves itself to be about 60% faster than yours:

use Benchmark qw/:all/;

my $string = "abracadabra";

cmpthese( 0, {
    c_regexp => sub { c_regexp( 'a' ) },
    c_index => sub { c_index( 'a' ) },
});

sub c_regexp {
    my ($c) = @_;
    my @matches = ($string =~ /$c/g);
    return scalar @matches;
}

sub c_index {
    my ($c) = @_;
    my $pos = -1;
    my $count = 0;
    $count++ while ($pos = index($string, $c, $pos + 1) ) > -1;
    return $count;
}


             Rate c_regexp  c_index
c_regexp 134878/s       --     -38%
c_index  216141/s      60%       --


             Rate c_regexp  c_index
c_regexp 130500/s       --     -40%
c_index  216412/s      66%       --

It's easy enough to add other attempts to compare ...



-----Original Message-----
From: perl-bounces at perl.org.il [mailto:perl-bounces at perl.org.il] On Behalf Of Gabor Szabo
Sent: Monday, September 03, 2007 14:18
To: Perl in Israel
Subject: Re: [Israel.pm] count chars

On 9/3/07, Amir E. Aharoni <amir.aharoni at gmail.com> wrote:
> What is the best way to count the number of times that a character
> appears in a string?
...
>
> It replaces the characters with itself and returns the number of
> substitutions, but it doesn't improve readability.

Whatever you do you can put it in a function

$n = count_chars($str, $c);

that will increase readability

Gabor
_______________________________________________
Perl mailing list
Perl at perl.org.il
http://perl.org.il/mailman/listinfo/perl


More information about the Perl mailing list