Another s*y question (cost of scaling and code diddling)

The Amazing Elvis Hypnodisk david at sun.com
Wed May 3 17:11:33 AEST 1989


In article <629 at gonzo.UUCP> daveb at gonzo.UUCP (Dave Brower) writes:
>Looking into this, I discovered at least one counter-intuitive result,
>Many people have jumped on this, but it does point to one of the
>fundamental C mind sets, which turns out to have some exceptions:
>
>	"For heavy array operations, it is usually faster to
>	use pointers than array indexing."
>			- me.
>
>That is because the scaling operation is only done once, when the
>pointer is incremented, rather than at each reference to the
>array[index].  Specifically, where a and b are arrays of non-char types:
>
>	for( ap = a, bp = b; i--;  ) /* even I will use a comma op here! */
>		*ap++ = *bp++;
>
>Is likely to be noticably faster than the functionally equivalent:
>
>	while( i-- )
>		a[i] = b[i];

Another counter-intuitive result is the Sun-4.  The current Sun SPARC C
compiler will usually generate better code for arrays than for pointers.
This is mostly because of the SPARC instruction set (it has reg + reg
addressing but no autoincrement or memory to memory ops).  The best
pointer code would be something like (neglecting loop unrolling):

1:	ld	[%ap], %tmp
	inc	size, %ap
	st	%tmp, [%bp]
	deccc	%i
	bnz	1b
	inc	size, %bp	! delay slot

while the best array code might be:

1:	ld	[%aend + %off], %tmp
	inccc	size, %off
	bnz	1b
	st	%tmp, [%bend + %off] ! delay slot

where aend = a + i, bend = b + i - 1, off = -i * sizeof *a, and of course
sizeof *a == sizeof *b.  Not that a compiler couldn't tranform one into
the other.  Not that I'm in the Sun compiler group.

Remember, cc -S is your friend.

-- 
David DiGiacomo, Sun Microsystems, Mt. View, CA  sun!david david at sun.com



More information about the Comp.lang.c mailing list