Array indexes vs. Pointers

Gary Tarolli tarolli at dragon.wpd.sgi.com
Tue May 23 01:01:48 AEST 1989


In article <33239 at sgi.SGI.COM>, ciemo at bananapc.wpd.sgi.com.SGI.COM (Dave Ciemiewicz) writes:
> To use pointers or array indexes, that is the question.  The SGI (MIPS) 
> compilers for the 4D are optimization monsters.  The optimizer is "smart"
> enough to recognize special case use of array indexes and convert them to
> pointers internally.  This removes the infamous multiply within your loop
> when using array indices.  The fact of the matter is that there are cases
> where use of indexes will generate more efficient code than the corresponding
> code using pointers.  The following is a C source file which demonstrates
> this.
> 
> ----- optimizer.c -------------------------------------------------------------
> /*  1 */extern v3f(float [3]);
> /*  2 */
> /*  3 */dovertices_indexed(float v[][3], unsigned int len) {
> /*  4 */    register unsigned int	i;
> /*  5 */
> /*  6 */    for (i=0; i<len; i++) {
> /*  7 */	v3f(v[i]);
> /*  8 */    }
> /*  9 */}
> /* 10 */
> /* 11 */dovertices_pointer(float v[][3], unsigned int len) {
> /* 12 */    register float ** 		p;
> /* 13 */
> /* 14 */    for (p=v; p != v+len*3; p+=3) {
> /* 15 */	v3f(*p);
> /* 16 */    }
> /* 17 */}
> ----- optimizer.c -------------------------------------------------------------

If I am not mistaken, the second example should be "v3f(p);" and not *p.  This
will remove the offending load word instruction and the possibility of missing
the cache and also make the second loop more efficient.

However, I agree with Dave, arrays are generally as efficient as pointers
and they are easier to read.  Also, it makes sense to use arrays and then
use prof to isolate your bottlenecks.  However, there is one case where
arrays are much faster than pointers on the MIPS cpu - and that is where
you are unwinding an autoincremented pointer loop.  For example,

    for (i=0; i<end; i+=4) {
	to[i] = from[i];
	to[i+1] = from[i+1];
	to[i+2] = from[i+2];
	to[i+3] = frompi+3];
    }

is much better than

    while (to < end) {
	*to++ = *from++;
	*to++ = *from++;
	*to++ = *from++;
	*to++ = *from++;
    }

because MIPS doesn't have an autoincrementing register instruction and the 
first case doesn't need to do the extra 2 adds per line of code. So sometimes
it is better to use base+offset then *p++.  Sometimes ...  on certain 
machines ....  when the moon is full ....



More information about the Comp.sys.sgi mailing list