Is there any benefit (w.r.t performance/memory usage) in including use mylibrary
conditionally (assuming mylibrary
is used only if condition is true) compared to adding use mylibrary
on top of the script unconditionally?
# Script 1 (Unconditional use)
use mylibrary;
if($condition)
{
# Do something with mylibrary
}
# Script 2 (Conditional use)
if($condition)
{
use mylibrary;
# Do something with mylibrary
}
use
is a compile-time construct. In your two cases, mylibrary
is actually being imported in both of your "Unconditional" and "Conditional" cases. If you want to import a library conditionally, use require
, a run-time construct, instead.
if ($condition) {
require mylibrary;
# mylibrary->import;
# ...
}
In such a case you lose some of the compile-time benefits of use
. For example, require
does not call mylibrary->import
at compile time, as use
does. You can call import
yourself if you want, as I show above, but anything import
does that has an effect at compile time will not have that effect when called at run time.
Suppose your module mylibrary
exports a function foo
. Then this works:
use strict;
use mylibrary; # exports function foo()
foo;
But this is an error:
use strict;
require mylibrary;
mylibrary->import; # too late to notify Perl's parser about the foo() function
foo; # error; unknown function
As to whether there's any benefit to doing so, there can be if mylibrary
is expensive to import. Most of the time, probably not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With