Understanding the Use of Nested Import and Selective Import in D

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Jan 16 23:53:05 UTC 2024


On Tuesday, January 16, 2024 1:42:04 PM MST bomat via Digitalmars-d-learn 
wrote:
> Wow, that was... exhaustive. Thanks for that. :)
> One more question that I have, though...
>
> On Tuesday, 16 January 2024 at 19:05:43 UTC, Jonathan M Davis
>
> wrote:
> > The downside of course is that you then have import statements
> > throughout your code, and they're often going to be duplicated
> > throughout a module (or even within a function if you localize
> > them far enough), because separate parts of the code then need
> > their own local imports.
>
> Apart from the aesthetic "clutter" of duplicate imports, will
> they also put additional strain on the compiler and/or affect the
> resulting binary? I mean, will the imports actually be compiled
> in several times?

Imports are never compiled in. Importing a D module is nothing like
#including a C/C++ header file. It does not result in any code being
inserted into the current module, and if it results in anything being added
to the binary, it's because a template from that module was instantiated
with a new set of arguments, resulting in a new template instantiation that
has to end up in the binary.

An import statement tells the compiler to allow the current code to use the
symbols from the imported module. That requires compiling the imported
module sufficiently for the compiler to then let those symbols be correctly
used within the module that's doing the importing, but importing a module
doesn't make it so that the compiler fully compiles the imported module. To
do that, the module has to also be passed to the compiler to be compiled (be
it as part of the same compilation process or compiled separately to be
linked in later).

And once a module has been imported, the compiler has already built the
symbol table for that module, so importing the module additional times
during the same round of compilation will not result in it being processed
again. The import statement will need to be parsed, which isn't free, but
it's so cheap in comparison to everything else that you'd likely have a very
hard time detecting the cost even in a very large codebase with a lot of
local import statements. And if anything, using local imports could reduce
compilation times, because if an import is local to a template, and your
code doesn't end up instantiating that template (or doesn't compile in a
particular branch of a static if or version block), then the compiler
doesn't need to do anything with that import.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list