Yet Another Silly Question

James C. Benz jcbst3 at unix.cis.pittsburgh.edu
Thu Jun 1 03:53:27 AEST 1989


In article <2550091 at hpisod2.HP.COM] decot at hpisod2.HP.COM (Dave Decot) writes:
]] 	int a[MAX];			int a[MAX];
]] 	int i;				int *p;
]] 	for (i=0; i<MAX; ++i)		for (p=&a[0]; p<&a[MAX]; ++p)
]] 		a[i] = 0;			*p=0;
]] 
]] 	...
]] 
]] ... On some compiler/machine combinations, this will run faster,
]] because the scaling operation and base/offset addition have been
]] eliminated; on others it may run slower, because a specific addressing
]] mode cannot be used.
]
]Note that the scaling operation has not necessarily been completely
]eliminated; it may have become hidden in "++p" because increments by 1
]may be much faster than increments by sizeof(*p).
]
Also, the scaling operation has simply been moved to the "for" line, as
far as I can tell.  The machine still has to dereference &a[MAX] on each
iteration of the loop, doesn't it?  It has to perform the test on each
iteration to see if p is < &a[MAX], and unless the optimizer is really
on top of things, it has no way of generating the comparison address
as a constant.  It really has no way of knowing that &a[MAX] won't
change during the course of the program, so it must be re-computed on
each iteration of the loop.  Seems to me that computing &a[MAX] will
take just as long and just as many arithmetic operations as computing
the address of a[i], with the minor difference between using a constant
as index as opposed to a variable.  In any situation I hope to encounter
in the kind of work I do, (database admin) I will trade off the readability
of the first example against the run time efficiency of the second, and 
choose readability every time.
-- 
Jim Benz 		     jcbst3 at unix.cis.pittsburgh.edu     If a modem 
University of Pittsburgh					 answers,
UCIR			     (412) 648-5930			 hang up!



More information about the Comp.lang.c mailing list