Using memcpy()
when source and destination overlap can lead to undefined behaviour - in those cases only memmove()
can be used.
But what if I know for sure buffers don't overlap - is there a reason to use specifically memcpy()
or specifically memmove()
? Which should I use and why?
Assuming a sane library implementor, memcpy
will always be at least as fast as memmove
. However, on most platforms the difference will be minimal, and on many platforms memcpy
is just an alias for memmove
to support legacy code that (incorrectly) calls memcpy
on overlapping buffers.
Both memcpy
and memmove
should be written to take advantage of the fastest loads and stores available on the platform.
To answer your question: you should use the one that is semantically correct. If you can guarantee that the buffers do not overlap, you should use memcpy
. If you cannot guarantee that the buffers don't overlap, you should use memmove
.
memcpy()
doesn't have any special handling for overlapping buffers so it lacks some checks therefore it is faster than memmove()
.
Also on some architectures memcpy()
can benefit from using CPU instructions for moving blocks of memory - something that memmove()
cannot use.
If you're interested in which will perform better, you need to test it on the target platform . Nothing in the standard mandates how the functions are implemented and, while it may seem logical that a non-checking memcpy
would be faster, this is by no means a certainty.
It's quite possible, though unlikely, that the person who wrote memmove
for your particular compiler was a certified genius while the poor soul who got the job of writing memcpy
was the village idiot :-)
Although, in reality, I find it hard to imagine the memmove
could be faster than memcpy
, I don't discount the possibility. Measure, don't guess.
On some ARM platform im working on, memmove was 3 times faster than memcpy for short unalligned load. As memcpy and memmove are the only truly portable type-punning mechanism, you would have thought that the would be some check by the compiler before trying to use the NEON to do it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.