Search code examples
perlperl-module

Save resources by only loading parts of a module?


I am reading through O'Reilly's Perl Objects, References & Modules, more specifically its section about modules. It states that when using use Some::Module you can specify an import list. From its explanation it seems that the only benefit of using this list is for the sake of keeping your namespace clean. In other words, if you have a subroutine some_sub in your main package and the loaded module has a sub with the same name, your subroutine will be overridden. However, if you specify an import list and leave out some_sub from this list, you'll not have this conflict. You can then still run some_sub from the Module by declaring it like so: Some::Module::some_sub.

Is there any other benefit than the one I described above? I am asking this because in some cases you load modules with loads of functionality, even though you are only interested in some of its methods. At first I thought that by specifying an import list you only loaded those methods and not bloating memory with methods you wouldn't use anyway. However, from the explanation above that does not seem the case. Can you selectively save resources by only loading parts of a module? Or is Perl smart enough to do this when compiling without the need of a programmer's intervention?


Solution

  • Note that "import list" is just a convention. Module's import function is free to do whatever it pleases with this list and you can see it (ab)used by many so-called pragma modules. Therefore partial loading is NOT bound to use in any way. For example module can load heavy function stubs WHEREVER you've imported them or not and dynamically load heavy implementation on actual first call.

    Therefore use with partial import list may, or may not actually save any resources - it is all depends on actual implementation of used module.

    While require and use indeed load entire .pm file - that file well could be just a lightweight stub and loader for actual code located elsewhere. There's another convention to call those modules ::Heavy.

    Modules are free to implement partial loading in any way they please as well. Here are just some possibilities how module can save resources:

    1. AUTOLOAD (with its complimentary AutoLoader, AutoSplit, and SelfLoader modules).
    2. Use stubs that load necessary submodules.
    3. Dynamically load heavy data (i.e. dictionaries or encoding maps) when they are first accessed by their name.
    4. If you depend on other heavy modules, dynamically require them at runtime in functions that depend on them instead of compile-time use at the very start.

    Everything on this list could work automatically behind the scenes, exposed through use import list, or work/be called in other, completely arbitrary way. Once again, it's completely up to module's implementation.