[vox-tech] perl - benchmark module

David Hummel dhml at comcast.net
Thu Jan 6 09:55:42 PST 2005


On Thu, Jan 06, 2005 at 12:07:25PM -0500, Peter Jay Salzman wrote:
> 
> I spent a minute playing with the benchmarking module and found some
> interesting stuff I thought others would find interesting too.
> 
> tr versus regex
> ===============
> Each piece of code was run 400,000 times and the "final time" is the
> total time divided by 400,000.
> 
> This code executes 412,371 times per second:
> 
>    $string = 'hello';
>    $string =~ tr/hello/olleh/;

$string is now "olllh";

> This code executes 180,995 times per second:
> 
>    $string = 'hello';
>    $string =~ s/hello/olleh/;

$string is now "olleh";

These are different operations.  I'll let you look into why.

> tr is clearly faster than regex.  At first, I was surprised that
> single character replacements took longer than word replacements, but
> upon reconsidering it, I think it's certainly plausible.

I think this is what you would expect.  Transliterations are not as
smart as regular expressions.  The tr/// operator simply replaces one
character set with another, character by character.  The s/// operator
compiles the entire string and executes it in the regex engine.

What happens if you precompile the string with the qr// operator?

-David


More information about the vox-tech mailing list