Outaspace has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I have a little question. I use constants in my script for debug messages, but I wondered if they need execution time. As I unstood the Perl Optimizer discards code that is never reached, but there seems to be "Optimization Levels" (right???). So does the following print in the code bother my script while executing? Would it make any difference if I delete those lines?
package Test; use constant DEBUG => 0;# There is also one in the main package, for t +urning all on sub new { print "Test->new(@_)" if (DEBUG || main::DEBUG); ... }

Humble,

Andre

Replies are listed 'Best First'.
Re: use constant and the Perl Optimizer
by ikegami (Patriarch) on Sep 19, 2006 at 16:55 UTC

    If both constants are false, the print and the if are removed at compile-time.

    If one or both constants are true, the if is removed at compile-time, leaving the print to execute unconditionally.

    By the way, the benefits of this are minuscule. You might save yourself a couple of seconds every 100,000 times you execute it. The time it takes to evaluate the conditional expression is dwarfed by the time it takes to call the function.

    Update:

    Rate var const var 765464/s -- -20% const 956589/s 25% --
    use Benchmark qw( cmpthese ); { package pkg1; use constant DEBUG => 0; our $DEBUG => 0; } { package pkg2; use constant DEBUG => 0; our $DEBUG => 0; } sub const { print "boo" if pkg1::DEBUG || pkg2::DEBUG; } sub var { print "boo" if $pkg1::DEBUG || $pkg2::DEBUG; } cmpthese(-3, { const => 'const(); 1;', var => 'var(); 1;', });
Re: use constant and the Perl Optimizer
by mreece (Friar) on Sep 19, 2006 at 17:41 UTC
    my hunch is it will not make a difference, and i think B::Deparse backs me up on this..
    $ perl -MO=Deparse -e ' > package main; > use Test; > use constant DEBUG => 0; > my $t = Test->new(); > > package Test; > use constant DEBUG => 0; > sub new { > print "Test->new(@_)" if ( DEBUG || main::DEBUG() ); > # ... > } > ' use Test; use constant ('DEBUG', 0); my $t = 'Test'->new; package Test; sub BEGIN { require constant; do { 'constant'->import('DEBUG', 0) }; } sub new { 0; } -e syntax OK