pagoda wrote:
> Can I improve the performance of script by using constant?
>
> Which is the better one?
>
> use constant const => 1e-12
>
> or
>
> my $const = 1e-12
>
> Thanks.
> just another perl beginner
I would think that use constant would be faster. Declaring a
scalar would still require the program to access the value of
that scalar whenever it is called. The use constant form
hard-codes the value wherever the constant appears, so there
is no dereference needed:
With use constant:
consant_test.pl:
#!perl -w
use strict;
use warnings;
use constant LIMIT => 25;
for (1..LIMIT) {
print "$_\n";
}
Greetings! E:\d_drive\perlStuff>perl -MO=Deparse
constant_test.pl
BEGIN { $^W = 1; }
use constant ('LIMIT', 25);
BEGIN {${^WARNING_BITS} = "UUUUUUUUUUUU"}
use strict 'refs';
foreach $_ (1 .. 25) {
print "$_\n";
}
constant_test.pl syntax OK
With a variable:
constant_test2.pl:
#!perl -w
use strict;
use warnings;
my $LIMIT = 25;
for (1..$LIMIT) {
print "$_\n";
}
Greetings! E:\d_drive\perlStuff>perl -MO=Deparse
constant_test2.pl
BEGIN { $^W = 1; }
use warnings;
use strict 'refs';
my $LIMIT = 25;
foreach $_ (1 .. $LIMIT) {
print "$_\n";
}
Using a constant does seem to add one more step to the
compilation process, since it sets the WARNING_BITS flag.
After that, though, there should be no runtime overhead relate
to accessing that value. Besides, it is more clear. If an
idetifier is a symbolic constant for a given value, that is a
different thing than a identifier that happens to be storing
the same value at a given moment.
Joseph
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]