- Which is faster, preprocessor (-P) or use constant pragma?
They both are the same.
- How did you find this out (better yet, aside from reading the
internals of the perl interpreter -- I am not ready, is there a way to
profile the compilation stage and where can I go to read/learn about
such things)?
You can use the B::Graph module to see how perl constructed the execution
tree for the code you've written. The only difference between the two is
that when you use constant, the constant needs to be initialized at the
top of the parse tree, while the preprocessed code does not have such
step.
- Once the optimizer strips out unnecessary code, at anytime in
recompilation (such as when an eval() gets compiled at run-time), does
this folded code effect the compilation time?
I believe once a portion of code is discarded, it is discarded forever.
In the example above, since you cannot change the value of the constant
UNDEF, there is really no point in keeping the stuff inside the if
statement.
Here is how I tested this:
#!/usr/bin/perl -P -MO=Graph,-text
use constant UNDEF => 0;
my $test = 1;
if(UNDEF){
$test = 'Hello World';
}
print "\$test => $test\n";
#!/usr/bin/perl -P -MO=Graph,-text
my $test = 1;
#if 0
$test = 'Hello World';
#endif
print "\$test => $test\n";
You can run these 2 programs:
./prog.pl | grep Hello to see if the
word "Hello" appears anywhere in the output. Also, if you use a variable
instead of a constant, (as in
my $UNDEF = 0; ), you'll see that the
statement will not be folded and that "Hello" will appear in the output.
Hope this answers your questions.
PS: -MO=Graph,-text will show you an ascii drawing of the tree, while -MO=Graph,-dot will output a dot file that you can view if you have dotty, part of the Graphviz package.