String copy idiom.

Bill Shannon shannon at sun.uucp
Mon Mar 11 19:16:59 AEST 1985


> In article <3448 at alice.UUCP> ark at alice.UUCP (Andrew Koenig) writes:
> >If s and t are char pointers in registers,
> >
> >	while (*s++ = *t++) ;
> >
> >generates the best code I could possibly imagine.
> >
> >	while ((*s = *t) != '\0') {s++; t++;}
> >
> >is considerably worse.  Try it with register variables on your compiler.
> 
> Ok, I did.  The second sequence generates less code than the first sequence
> on our machine (Perkin-Elmer).  This is due to the fact that our machine
> doesn't support auto-increment in hardware.  The C compiler has to "fake" it.
> 
> 					regards,
> 					joe

On the Sun the first generates the obvious two instruction loop
while the second generates a five instruction loop:

	register char *s, *t;
	while (*s++ = *t++) ;

L14:
	movb	a4 at +,a5 at +
	jne	L14

	while ((*s = *t) != '\0') {s++; t++;}
L17:
	movb	a4@,a5@
	jeq	LE12
	addql	#1,a5
	addql	#1,a4
	jra	L17
LE12:

Note that the two loops differ in the values of s and t at loop
termination.  I consider the first loop to be more obvious, it
is after all the standard C idiom for copying a string.  If you
"optimize" your code for one machine by writing the second loop,
you may be pessimizing it for other machines.  Such is the nature
of C and C programmers.

					Bill Shannon
					Sun Microsystems, Inc.



More information about the Comp.lang.c mailing list