Issue 19874 - imported CTFE static initializers are run for no reason
Summary: imported CTFE static initializers are run for no reason
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P3 normal
Assignee: No Owner
URL:
Keywords: CTFE, performance
Depends on:
Blocks:
 
Reported: 2019-05-15 08:44 UTC by Steven Schveighoffer
Modified: 2022-12-17 10:37 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Steven Schveighoffer 2019-05-15 08:44:43 UTC
If you import a module that has a static initializer for a mutable variable that obviously cannot be used at compile time, and that imported module isn't being compiled, the compiler should NOT run the CTFE function, as long as it can know the type without running it.

For example:

-----
string buildModData()
{
    string result;
    foreach(i; 0 .. 10000)
        result = result ~ "lots and lots and lots of data";
    return result;
}

string moddata = buildModData(); 
----

buildModData should not be run at compile time if this is simply imported, because the compiler isn't going to store it anywhere. My system consumes 1 second to import this file, regardless if I use moddata or not.

In addition, even if the variable is type-inferred:

---

static moddata = buildModData();
---

This should still not result in CTFE execution because the type is clear from the function definition. Essentially, only the TYPE is important here, not what the value is, since it's not readable at compile time anyway.

I would also wish to have the value left uncalculated even if the value IS readable at compile time, but is not used. This may be a more difficult problem to solve, as it requires lazy evaluation of imported items.

See forum thread: https://forum.dlang.org/post/qbckmt$1oks$1@digitalmars.com