jbisbee has asked for the wisdom of the Perl Monks concerning the following question:
and if you use that in an if statement, then the entire if block will get compiled out if its false with no penalty at run time. I wanted to show how this works in my presentation and decided to run this sample code through B::Deparse to show how its optimizeduse constant DEBUG => 0;
I was suprised when I got this from the output of perl -MO=Deparseuse strict; use warnings; use constant DEBUG => 0; print "Hello World\n"; print "This is a debug Statement\n" if DEBUG; print "Goodbye Cruel Word\n";
I thought to myself, "WTF is this '???'; string in void context, I assumed it would just remove the line". Now this isn't a huge deal because a string in void context is infinitely faster that an if statement, but I was surprised to see it. So surprised that I decided to bench it.use constant ('DEBUG', 0); use warnings; use strict 'refs'; print "Hello World\n"; '???'; print "Goodbye Cruel Word\n";
And was surprised by the results...use strict; use warnings; use Benchmark qw( cmpthese ); use constant DEBUG => 0; my $b = 100; cmpthese -10, { constant => sub { my $a = 10 * $b; $a = 10 * $b if DEBUG; }, noconstant => sub { my $a = 10 * $b; }, };
I mentioned my findings at our Perl Monger meeting last night and Rocco Caputo was also under the same assumption that there was zero penalty for using constants and they were compiled out.Rate constant noconstant constant 1498536/s -- -17% noconstant 1796946/s 20% --
Of course the penalty is _very_ small, but what's the point of the '???'; and why not just compile it out as I've heard over and over - the big benefit of using optimized subs as constants (use constant DEBUG => 1; or sub DEBUG () { 1 })
I also noticed that instead of ???; sometimes it gets compiled down to 0;
-biz-
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: use constant and Compiler Optimizations
by almut (Canon) on Jul 18, 2008 at 17:05 UTC | |
Re: use constant and Compiler Optimizations
by Joost (Canon) on Jul 18, 2008 at 19:58 UTC | |
by ikegami (Patriarch) on Jul 18, 2008 at 20:16 UTC | |
by Joost (Canon) on Jul 18, 2008 at 20:43 UTC | |
by BrowserUk (Patriarch) on Jul 18, 2008 at 22:26 UTC | |
Re: use constant and Compiler Optimizations
by ikegami (Patriarch) on Jul 18, 2008 at 20:21 UTC |