Passing arguments a template parameters vs. function parameters

Craig Dillabaugh cdillaba at cg.scs.carleton.ca
Tue Jun 11 14:40:14 PDT 2013


On Tuesday, 11 June 2013 at 21:26:35 UTC, John Colvin wrote:
> On Tuesday, 11 June 2013 at 20:46:32 UTC, Craig Dillabaugh 
> wrote:
>> I was looking at D code for constructing kd-trees, the full 
>> code
>> listing for which can be found here:

clip

>>
>> 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.
>>
>> Cheers,
>> Craig
>
> It's just a trade-off between template bloat and having more 
> values hard-coded in for efficiency.
>
> In this particular case, due to the use of the static array in 
> KdNode, if idx is known at compile time then the optimizer can 
> go to town on those loops in findMedian. e.g. in
>
> foreach (p; start .. end) {
>     if (p.x[idx] < pivot) {
>         if (p != store)
>             swap(p.x, store.x);
>         store++;
>     }
> }
>
> given offset = p.x.offsetof + idx
> p.x[idx] becomes just *(p+offset) which is fast and completely 
> predictable behaviour. Great for optimizers and cache 
> prefetching etc...
>
>
> All that is meaningless guesswork though, the only thing that 
> will tell you for sure is benchmarking and profiling.

Thanks. This makes sense. If I can find the time perhaps I will
run some benchmarks on it.



More information about the Digitalmars-d-learn mailing list