SPUG: Using subroutines to return constants

Jim Flanagan jimfl at colltech.com
Sat Nov 4 13:22:58 CST 2000


On Sat, 4 Nov 2000, Richard Anderson wrote:

      > 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:
      > 
      > Any thoughts on this?

  If you prototype a subroutine with a null arglist, and the subroutine
  returns a constant value, then the compiler inlines all of the constant
  references, and no subroutine call actually takes place at runtime.

  Consider the following code:

    use Benchmark;

    my $VARIABLE = 10;
    sub SUBCONST () { 10 };
    use constant PRAGCONST => 10;

    timethese 1000000,
      { variable => sub {$v = $VARIABLE},
	pragma   => sub {$v = PRAGCONST},
	inline   => sub {$v = SUBCONST} };

  This gives:
 
    Benchmark: timing 1000000 iterations of inline, pragma, variable...
	inline:  4 secs ( 2.14 usr  0.00 sys =  2.14 cpu)
	pragma:  3 secs ( 2.14 usr  0.00 sys =  2.14 cpu)
      variable:  2 secs ( 2.19 usr  0.00 sys =  2.19 cpu)

  The pragma is doing essentially the same thing as the inlined subroutine,
  except that it is inserting the subroutine definition right into the
  namespace of the calling routine.

  Note that my numbers have to be taken with a grain of salt because my
  Benchmark.pm (RatHead Linux 5.x) seems to be wacky.

-- 
Jim Flanagan        Collective Technologies
jimfl at colltech.com  http://www.colltech.com


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