Compile Time versus Run Time

Marco Leise via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jul 31 09:20:56 PDT 2017


Am Mon, 31 Jul 2017 15:43:21 +0000
schrieb Martin Tschierschke <mt at smartdolphin.de>:

> As a rookie in D programming I try to understand the power of 
> templated functions with compile time parameters. With DMD 2.074 
> a compile time format
> (auto output = format!("Print this %s")(var);)
> 
> was introduced, now we all know that very many of this format 
> strings are immutable, so wouldn't it be cool to automatically 
> detect this and use the compile time version?
> 
> Without the need to think about it and to use an other syntax?
> Is this theoretically possible?

I see no way to accomplish this. For the compiler to see the
contents of the format string it needs to be a template
argument and as soon as you want to also allow runtime values
to be accepted there, you need to use an alias, which in turn
precludes the use of function results or concatenation.
Believe me I've spent quite some time on trying something like
this for format strings.
 
> Regards mt.

As far as using template arguments for code optimizations go, I
know that at least GCC will turn runtime arguments into
template arguments of sorts internally, thereby creating
duplicates of the function with one or more arguments
optimized out.
On the other hand, you don't want to drive this too far. While
it is nice to have compile-time checks, templates are actually
troublesome on some levels. For example, the duplicated code
makes it hard to cache the formatting function in the CPU and
when writing libraries you always have to provide the full
implementation that will get linked into the host application,
which is a concern under certain licensing schemes.
The benefits of shared libraries, like loading the code into
memory once and use it by multiple processes or fixing
security issues in one central place and have all programs use
the new code without recompilation are also void. I.e. without
template arguments, `format()` and all its dependencies
(templates as well as regular functions) are compiled right
into the Phobos shared library for all programs to use. If
there is a security issue, it can be replaced with a patched
version. Now with template arguments, `format!()` is compiled
into each Dlang application multiple times for each format
string and security fixes cannot be applied without
recompiling them all.

-- 
Marco



More information about the Digitalmars-d-learn mailing list