[vox-tech] perl - benchmark module

Peter Jay Salzman p at dirac.org
Thu Jan 6 09:07:25 PST 2005


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/;

This code executes 180,995 times per second:

   $string = 'hello';
   $string =~ s/hello/olleh/;

This code executes 416,666 times per:

   $string = 'hello'; 
   $string =~ tr/h/j/;

This code executes 195,121 times per second:

   $string = 'hello';
   $string =~ s/h/j/; 


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.



"my" variables
==============

   53,763 times/sec:

   for ( my $i = 0;  $i < 10;  ++$i ) { my $var = $i; }


   58,823 times/sec:

   for ( my $var, my $i = 0;  $i < 10;  ++$i ) { $var = $i; }


   58,997 times/sec

   my $var;
   for ( my $i = 0;  $i < 10;  ++$i ) { $var = $i; }

The last two might be insignificantly different.  But it does show that
declaring a "my" variable, while not costly, isn't free either.


$i++ versus ++$i
================
I read somewhere that there are "theoretical considerations" where ++i can
be faster than i++ in C++.  Don't remember the details, but I figured I'd
give it a whirl on Perl.  The following code times were averaged over
1,000,000 trials.  They both executed 80,064 times/sec.

   for ( my $i = 0; $i < 10; $i++ ) {}

and

   for ( my $i = 0; $i < 10; ++$i ) {}



Memory Free Parenthesis
=======================
This is in all the "optimizing Perl" books.  Thought I'd take a look at it
myself.  Code was executed 500,000 times.  It is about 20% faster using
memory free grouping.

42,918 times/sec:

   $string = "Hello, Dolly.  This has been a pleasure.";
   $string =~ s/(This|That)/It/;

53,404 times/sec:

   $string = "Hello, Dolly.  This has been a pleasure.";
   $string =~ s/(?:This|That)/It/;


This was fun, but it's time to get back work.  :)

Pete

-- 
The mathematics of physics has become ever more abstract, rather than more
complicated.  The mind of God appears to be abstract but not complicated.
He also appears to like group theory.  --  Tony Zee's "Fearful Symmetry"

GPG Fingerprint: B9F1 6CF3 47C4 7CD8 D33E  70A9 A3B9 1945 67EA 951D


More information about the vox-tech mailing list