Use of templates to avoid redudancy of code

janderson askme at
Wed Jun 4 00:21:28 PDT 2008

Mael wrote:
> Hello,
> I'm writing an algorithm that has, say, too possible behaviour depending on a switch. Since there are many imbricated loops, and the behaviour change is inside the loop, testing for the flag is time-consuming
> for( ....)
> for( .... )
> for( ... )
> {
>   if( flag ) action_1 ;
>   else action_2 ;
> }

If the flag is dependent on something in the loop, you could try storing 
your stuff in buckets (maps, arrays, sorted array or whatever works). 
That way you know what is in each group to begin with.

> is there a clean way to use templates to generate the duplicate of the code like
> if( flag )
> {
>   for(...) .... action1 ;
> }
> else
> {
>   for(...) .... action2 ;
> }

Ok, so you've created some sort of bucket thing, great!

Assuming that flag is not an object with a very expensive compare.  If 
you've profiled it and found its a problem (based on algorithm 1) then 
it means that action_1 and/or action_2 are doing very, very little work 
and you are traversing many items.  I'm imagining its either an 
assignment or comparison.  In fact you would likely get more of a 
speedup by unrolling the loop then anything else.  Note that for does a 
comparison and a ++ each iteration.   Anyway hope that helps explain why 
other people in the NG immediately raised the pink premature 
optimisation warning flags.

Ok down to my thoughts on optimizing this:

Given that action_1 and action_2 are probably small ops; If you want 
optim performance you could take advantage of SIMD or futures (parallel 
processing) or there may be a function already that's ASM optimized to 
do what you want (memcopy, memset etc...)

Another possibility is to change the array your iterating over:

array = (flag) ? array1 : array2;
for (auto value; array)


Note you save a branch that way, but that would very likely be 

I hope this has been helpful.

More information about the Digitalmars-d-learn mailing list