Efficient Coding Practices

Richard A. O'Keefe ok at quintus.uucp
Tue Oct 4 06:54:08 AEST 1988


In article <34196 at XAIT.Xerox.COM> g-rh at XAIT.Xerox.COM (Richard Harter) writes:
>>!	tmp1 = dst;
>>!	tmp2 = src;
>>!	for (i=0;i<n;i++) *tmp1++ = *tmp2++;

>In many machines it is more
>efficient to control loops by counting a register down to zero and escaping
>on zero than it is to exit on a compare.  A good compiler will do exactly
>that with the sample code.

This is only true if the machine's loop control instructions fit the loop
in question *very* closely.  For example, at least some MC680x0 C compilers
will generate DBcc loops for neither of these forms:
	for (i = 0; i < n; i++) <stmt>
	for (i = n; --i >= 0; ) <stmt>
Instead, you have to write
	for (i = n-1; --i != -1; ) <stmt>

>Lesson:  If efficiency is a concern, countdown loops are faster than
>compare value loops.

>Lesson:  If one is optimizing code one has to think about what the machine
>will have to do in different implementations when comparing them.

Lesson: the 2nd lesson above renders the 1st moot.  Countdown loops may be
faster than others.  Or they may be slower.  Or it might depend on the size
of the count variable.  And it depends on the compiler as well as the machine.

Lesson: looking for a way to avoid the loop entirely is going to pay off on
most machines, tweaking it for one machine may make it very bad for another.



More information about the Comp.lang.c mailing list