Lazy Loading
Lazy Loading is a technique for performance optimisation. The idea is not to load code modules into memory until you are sure they are going to be required.
For example, consider a plugin module called
FrobnozzPlugin that requires the Perl modules
TWiki::Contrib::Frob and
TWiki::Contrib::Nozz to process
%FROBNOZZ% tags. These two modules are not required by the TWiki core, so they are only loaded by the plugin.
Normally you would put the lines:
use TWiki::Contrib::Frobb;
use TWiki::Contrib::Nozz;
at the top of
FrobnozzPlugin.pm. However, this makes the Perl compiler load these two modules each time the plugin is "discovered" by the TWiki core, whether the text to be rendered contains any
%FROBNOZZ% tags or not.
To avoid this inefficiency it is better to
use these modules only if they are required, by lazy loading them when the tag is seen.
use vars qw ( $initialised );
BEGIN {
$initialised = 0;
};
sub commonTagsHandler {
$_[0] =~ s/%FROBNOZZ%/&_handleFrobnozz()/ge;
}
sub _handleFrobnozz {
unless ( $initialised ) {
eval 'use TWiki::Contrib::Frobb';
if ( $@ ) {
TWiki::Func::writeWarning("Failed to use Frobb: $@");
return;
}
eval 'use TWiki::Contrib::Nozz';
if ( $@ ) {
TWiki::Func::writeWarning("Failed to use Nozz: $@");
return;
}
$initialised = 1;
}
...
}
Lazy loading can give significant performance improvements, especially where the referenced modules are large.
--
CrawfordCurrie - 13 Aug 2004
--
WillNorris - 13 Aug 2004
on the flip side, without a good code coverage set of tests (or people that don't run those tests before commiting) lazyloading produces hidden bugs
--
SvenDowideit - 23 Jul 2006