Efficient Coding Practices

Richard Harter g-rh at XAIT.XEROX.COM
Sun Oct 2 01:55:21 AEST 1988


In article <836 at proxftl.UUCP> bill at proxftl.UUCP (T. William Wells) writes:

>At one time, I spent a lot of my spare time improving other
>people's code.  One of the things I discovered is that almost all
>the code I was dealing with had better than 25% execution time
>fat.  What I mean is that when I merely changed all of the code
>to follow my coding practices (which are not anything special,
>just obvious things that every coder ought to know), it got that
>much better; I am not talking about mere tweaks, nor am I talking
>about optimizing particular sections of code.  I am talking about
>reading each line of code and making obvious changes (things like
>using temporaries when needed, adding appropriate register
>declarations, eliminating obviously unnecessary function calls,
>etc.)

	I would say that we all know what Bill is talking about
here, except that "we" all obviously don't.  Basically this is 
using hand optimization as a default in coding style.  One can take
the view that a good optimizer will do many of these things, e.g.
use of temporaries, moving static expressions outside loops, placing
the appropriate variables in registers, etc.  One can also take the
view that the capabilities and realities of optimizing compilers are
less than claimed.  Hand optimizing is safer across a variety of
environments.

	In my experience hand optimizing in original code is less
efficient, in the sense of code written per unit time, then writing
code initially in a "clear" style first, and then hand optimizing
afterwards.  In short, write it in the simplest way first, get it
working, and then improve performance.

	... Discussion of practical superiority of pointers deleted.

	Let me give a simple example.  Ignoring library routines,
inline routines, etc, suppose that we want to copy n bytes from one
place to another, say array src to array dst.  We might write

	for(i=0;i<n;i++) dst[i]=src[i];

Let's hand optimize this.  Instead of using indices (presumably less
efficent) we will use pointers.  Since we don't want to destroy dst
and src as pointers we need temporaries.  Thus we might write

	tmp1 = dst;
	tmp2 = src;
	for (i=0;i<n;i++) *tmp1++ = *tmp2++;

[Leave us not worry about whether there is a more efficient way to
handle the loop control.]  The "optimized" version requires more
statements; it requires more variables.  
-- 

In the fields of Hell where the grass grows high
Are the graves of dreams allowed to die.
	Richard Harter, SMDS  Inc.



More information about the Comp.lang.c mailing list