Efficiency Question

Checkpoint Technologies ckp at grebyn.com
Tue Feb 26 15:20:23 AEST 1991


rg2c+ at andrew.cmu.edu (Robert Nelson Gasch) writes:

>Since C gives you the opportunity to condense statements, I was wondering
>what difference to the compiler these 'shortcuts' make. 
>
>   x = x + 1;           can become
>   x += 1;              which can be further condensed to
>   x++;

There's not much reason to use the first form, that I can see. Unless
you're a die-hard Fortran programmer.

The second form as it stands has no real advantage over the third.
On the other hand, consider this fragment:

#define H_WIDTH 1
   int x;                /* current horizontal position */

   /* I draw a (skinny) graphic figure of width H_WIDTH.  Then: */
   x += H_WIDTH;        /* move drawing pen by figure width */  <- versus
   x++;

The first conveys more semantics to the reader.  The second *may* be
faster.  If so, that's tough luck, I still wouldn't use it.  I might
even be willing to argue that the second is *incorrect* in this case.

In article <1991Feb25.181434.6462 at ux1.cso.uiuc.edu> gordon at osiris.cso.uiuc.edu (John Gordon) writes:
>	In the above case, the last statement is definitely faster than the
>first one.  Because: in the first statement, the machine has to load 3 
>values into 3 registers and deal with them, whereas in the last statement,
>essentially only 1 register is being used.

Sorry, this has a lot to do with the machine and compiler involved.  Many will
compile all three forms to exactly the same thing (which you admit
later).

I may make a generalization, that a lot of
programmers make assumptions about what C compilers do, by observing
what a particular implementaiton does.  I prefer to assume that the C
compiler will generate code to implement the algorithm I coded, rather
than pick on it's instruction and register usage.  I have plenty of
other things to worry about.

Disclaimer: I don't write real-time code in C. This may be an environment
where nit picking is justified. I'd still rather find faster algorithms
than agonize over such tiny optimizations.
-- 
First comes the logo: C H E C K P O I N T  T E C H N O L O G I E S      / /  
                                                                    \\ / /    
Then, the disclaimer:  All expressed opinions are, indeed, opinions. \  / o
Now for the witty part:    I'm pink, therefore, I'm spam!             \/



More information about the Comp.lang.c mailing list