lazy import, an alternative to DIP 1005
Jonathan Marler via Digitalmars-d
digitalmars-d at puremagic.com
Fri Sep 15 14:45:01 UTC 2017
DIP 1005 proposes a solution to prevent loading in modules that
don't need to be loaded, thereby decreasing the overall compile
time. Here's an example taken from the DIP:
with (import std.stdio) void process(File input) ;
with (import std.range) struct Buffered(Range) if
(isInputRange!Range)
{
...
}
I've come up with another way to solve this problem by using a
modified version of import, call it a "lazy import". A lazy
import works like a "static import" in that all references to it
must be fully qualified, but it also delays loading the module
until absolutely necessary. Since all the symbols will be fully
qualified the semantic analyzer will know when it's time to load
the module. The previous example could be done like this:
lazy import std.stdio;
lazy import std.range;
void process(std.stdio.File input) ;
struct Buffered(Range) if (std.range.isInputRange!Range)
{
...
}
Note that instead of introducing the "lazy" modifier here, we
could just modify static imports to be lazy which would mean no
new syntax and every benefits from the feature without changing
their code, that is, if they are using static imports :)
aliasing can also be helpful in this instance
alias stdio = std.stdio;
alias range = std.range;
void process(stdio.File input) ;
struct Buffered(Range) if (range.isInputRange!Range)
{
...
}
Note that this usage is only meant for large library code like
phobos, where this type of optimization can have a big
performance impact when importing modules from the library. You
wouldn't use the verbose syntax from either of the examples in a
normal application.
What do you think, better or worse than DIP 1005? I think it's
simpler, but not sure if it's better overall.
More information about the Digitalmars-d
mailing list