Passing arguments a template parameters vs. function parameters

bearophile bearophileHUGS at lycos.com
Tue Jun 11 15:13:17 PDT 2013


Craig Dillabaugh:

> If I had been coding this I would almost certainly have passed
> the splitting dimensions as a function parameter, since the
> compiler has to generate separate makeTree/findMedian functions
> for each dimension that i/idx takes in the program.
>
> So my question is, does anyone have any idea why the author may
> have used templates here. It was on Rosettacode so maybe they 
> are
> just there to show off D's nice template abilities, but I am
> curious if in idiomatic D using templates this way is somehow
> superior to the function parameter method I would have tried.

That code was adapted by me from C code written by another person 
(I think Ledrug, a very good C programmer). I am maintaining all 
the many D entries of Rosettacode (plus few in other languages).

John Colvin explains the point of passing that argument as 
template argument instead of run-time argument. The number of 
dimensions is limited (often 2 or 3), to for this program the 
amount of generated template bloat is acceptable. Knowing the 
axis at compile-time should allows the compiler to perform better 
optimizations.
Beside binary size, the other disadvantage of template bloat is a 
pressure increase on the 16 kb of the half of L1 code cache of 
the CPU. So there are always trade-offs.


> If I can find the time perhaps I will run some benchmarks on it.

If you want to do benchmarks don't forget to do them with a 
better compiler, like LDC2, that is able to use that compile-time 
information to optimize better.

When I have written that code I was using only DMD. I have just 
started to use LDC2 and I have not yet timed that particular 
program with LDC2.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list