On Sat, Jul 21, 2001 at 01:16:04PM +0900, [EMAIL PROTECTED] wrote:
> 
> Matthew Fischer <[EMAIL PROTECTED]>wrote:
> >What is the best way to find the number of occurences of a specific
> >character in a string? I have some form data which is in a variable
> >$FORM{'countries'}, and I need to know how many pipe characters are
> >contained within it.
> 
> At 8:56 PM -0700 20/07/01, Dick Applebaum wrote:
> >     $x='123|456||78|9|';
> >     $z=$x=~s/\|/\|/g;
> >     print "$x\n";
> >     print "$z\n";
> 
> 
> tr/// is slightly more efficient than s///,

I think you underestimate the efficiency of tr/// for counting characters
:)


#!perl

use Benchmark;

$x = 'abc' x 10;

timethese( -3, {
  's'  => sub { $x =~ s/a/a/g; },
  'tr' => sub { $x =~ tr/a//; },
});

__END__

Benchmark: running s, tr, each for at least 3 CPU seconds...
   s:  4 wallclock secs ( 3.04 usr +  0.00 sys =  3.04 CPU) @ 40420.72/s (n=122879)
  tr:  5 wallclock secs ( 2.99 usr +  0.01 sys =  3.00 CPU) @ 156540.00/s (n=469620)

156,540 iterations per second for tr///, but only 40,420 per second for
s///g.

And with longer strings, the difference is even more significant.


Ronald

Reply via email to