String copy idiom.
Chris Torek
chris at umcp-cs.UUCP
Sat Mar 9 20:17:56 AEST 1985
> while (*s++ = *t++);
> ... this code produces a loop with 50% more assembler instructions
> than the slightly clearer sequence:
> while ((*s = *t) != '\0')
> { s++;
> t++;
> }
Not necessarily. It depends on whether s and t are "register" variables.
(The casual reader should type 'n' at this point . . . .)
Proof:
f(s, t)
register char *s, *t;
{
while (*s++ = *t++);
}
generates (optimized):
.globl _f
_f: .word 0xc00
movl 4(ap),r11
movl 8(ap),r10
L16: movb (r10)+,(r11)+
jneq L16
ret
while
g(s,t)
char *s, *t;
{
while (*s = *t) s++, t++;
}
generates (also optimized):
.globl _g
_g: .word 0
jbr L16
L2000001:
incl 4(ap)
incl 8(ap)
L16: movb *8(ap),*4(ap)
jneq L2000001
ret
Changing s and t above to "register char *" gives
.globl _g
_g: .word 0xc00
movl 4(ap),r11
movl 8(ap),r10
jbr L16
L2000001:
incl r11
incl r10
L16: movb (r10),(r11)
jneq L2000001
ret
which is faster most of the time (for strings of length 0 and 1 it's
probably slower).
It is true, however, that using postincrement on non-register pointer
variables is generally less efficient than doing the same thing "by hand",
since the compiler has to put the original value in a scratch register
so that the increment doesn't clobber the condition codes.
--
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 4251)
UUCP: {seismo,allegra,brl-bmd}!umcp-cs!chris
CSNet: chris at umcp-cs ARPA: chris at maryland
More information about the Comp.lang.c
mailing list