memcpy versus assignment

Henry Spencer henry at utzoo.uucp
Sun Dec 31 11:59:04 AEST 1989


In article <1657 at uwm.edu> chad at csd4.csd.uwm.edu (D. Chadwick Gibbons) writes:
>In several books I've seen that assignment of structures is usually
>more efficient than using memcpy(), at leant on most modern
>processors...
>In _general_ what is the rule for the assignment of two large
>structures?  memcpy vs. assignment?  Which is generally better?

With a good and fully modern compiler, there is no reason why there should
be any difference in efficiency.  It's the same operation, a block copy.
An ANSI C implementation is entitled to recognize memcpy() and produce 
inline code, although it might have to invest significant effort to be sure
that certain helpful constraints which are implicit in assignment are being
observed by the memcpy.

With poor or old compilers, it's an open question.  Many such compilers
will not inline memcpy(), and the function-call overhead will hurt.  On
the other hand, many such compilers will generate simple rather than
optimal copy code for the assignment, while the memcpy() may be well
optimized once you get past the startup overhead.  (In particular, there
is a naive belief that hardware provisions for fast copy -- string/block
instructions, "loop mode", etc. -- are always the fastest way to do such
operations, which is often untrue.  The clever tricks that can get you
a factor of 2 or more over hardware instructions are more often found
in library routines, because modifying compilers is harder and few
benchmarks use struct assignment much.)  (Lest anyone think I'm kidding
about the factor of 2, I've got an experimental memchr() which, on long
strings, beats every manufacturer's implementation we've tested by a
factor of at least 2 and usually 3-4... despite being written in portable
C rather than assembler.)

Unless efficiency is crucial, in which case you're probably tuning to match
the characteristics of a specific compiler anyway, you should use the form
which expresses your intent better and communicates it more clearly to the
compiler.  I.e., if you want to assign a structure, use assignment.
-- 
1972: Saturn V #15 flight-ready|     Henry Spencer at U of Toronto Zoology
1989: birds nesting in engines | uunet!attcan!utzoo!henry henry at zoo.toronto.edu



More information about the Comp.lang.c mailing list