develooper Front page | perl.perl5.porters | Postings from December 2001

why sub NAME () { 0 }

From:
Jeffrey Friedl
Date:
December 21, 2001 21:44
Subject:
why sub NAME () { 0 }
Message ID:
200112220544.fBM5iAR20335@ventrue.corp.yahoo.com

I understand using

   sub SOMETHING() { 123 }

if you want to export a bareword constant, like O_CREAT and the like.

But occasionally, I see the same thing for internal-use only, as in
lib/utf8_heavy.pl (which has code that seems to get invoked when various
Unicode-related things appear in regexes, like \p{Lu}, etc.)


    sub DEBUG () { 0 }
       :
       :
    print STDERR "......" if DEBUG;


This is a lot slower than just using a variable:

    my $DEBUG = 0;
       :
       :
    print STDERR "......" if $DEBUG;

and in hot code like utf8_heavy, I'd think that faster is better.

Any idea why DEBUG() is used?

    Jeffrey

---------------------------------------------

Here's the benchmark code I used:

        use strict;
        use warnings;
        use Benchmark ();

        sub DEBUG { 1 };

        our $DEBUG = 1;

        our $rDEBUG;
        *rDEBUG = \1; ## sets $rDEBUG as a constant

        our $x = 0;
        our $y = 0;
        our $z = 0;

        Benchmark::timethese(5_000_000, {
             Sub => '$x++ if DEBUG()',
             Var => '$y++ if $DEBUG',
             Ref => '$z++ if $rDEBUG',
        });

and the results:

  Benchmark: timing 5000000 iterations of Ref, Sub, Var...
    Var:  1 wallclock secs ( 1.70 usr +  0.03 sys =  1.73 CPU) @ 2890173.41/s
    Ref:  1 wallclock secs ( 1.73 usr + -0.05 sys =  1.68 CPU) @ 2976190.48/s
    Sub: 11 wallclock secs (12.11 usr +  0.03 sys = 12.14 CPU) @  411861.61/s



nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About