SPUG: Using subroutines to return constants

Richard Anderson starfire at zipcon.net
Sat Nov 4 11:25:21 CST 2000


Subtitle: Structured coding best practice or performance-crippling hack?

Although Perl 5.6 has the convenient constant declaration to fix the value
of a variable, most of us are still coding without this bit of syntactic
sugar.  The traditional way to refer to a constant in Perl is to use a
reference to a subroutine that does nothing but return the constant:

$PI = sub { 3.1415962 };

Subroutine calls are much slower than variable references, but how much
slower?  Here's some code that tests this:

$VARIABLE = 10;
$SUBREF = sub { 22; };

use Benchmark;
$count = 1000000;
$t = timeit($count, '$var = $VARIABLE');
print "$count loops of a variable reference took:",timestr($t),"\n";

$t = timeit($count, '$var = $SUBREF->()');
print "$count loops of subroutine reference took:",timestr($t),"\n";

I get a performance slowdown factor of 7 for the subroutine call on both
Windows and Linux.  Pretty nasty hit just to make your code cleaner.

Any thoughts on this?

Richard.Anderson at rayCosoft.com       RayCosoft, Professional Services Group
Perl/SQL/Unix software engineering    www.rayCosoft.com
www.zipcon.net/~starfire/home              Seattle, WA, USA


 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
  Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/





More information about the spug-list mailing list