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: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] 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 <[EMAIL PROTECTED]> 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
[email protected]
http://perl.org.il/mailman/listinfo/perl
_______________________________________________
Perl mailing list
[email protected]
http://perl.org.il/mailman/listinfo/perl