Newsgroups: comp.lang.c Path: utzoo!henry From: henry@utzoo.uucp (Henry Spencer) Subject: Re: memcpy versus assignment Message-ID: <1989Dec31.005904.1910@utzoo.uucp> Organization: U of Toronto Zoology References: <1657@uwm.edu> Date: Sun, 31 Dec 89 00:59:04 GMT In article <1657@uwm.edu> chad@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@zoo.toronto.edu