I have seen the difference pointed in the accepted answer in What is the difference between memmove and memcpy? and it said memmove might be very slightly slower than memcpy
.
We can implement an alternative for memmove
by doing as follows: allocate a temporary buffer, then memcpy
twice (src -> tmp, tmp -> dest). My question is: which way is faster, memmove
or the alternative?
From http://en.cppreference.com/w/cpp/string/byte/memmove
Despite being specified "as if" a temporary buffer is used, actual implementations of this function do not incur the overhead of double copying or extra memory. For small count, it may load up and write out registers; for larger blocks, a common approach (glibc and bsd libc) is to copy bytes forwards from the beginning of the buffer if the destination starts before the source, and backwards from the end otherwise, with a fall back to std::memcpy when there is no overlap at all.
Therefore the overhead in all likelihood is a couple of conditional branches. Hardly worth worrying about for large blocks.
However, it is worth remembering that std::memcpy
is a 'magic' function, being the only legal way to cast between two dissimilar types.
In c++, this is illegal (undefined behaviour):
union {
float a;
int b;
} u;
u.a = 10.0;
int x = u.b;
This is legal:
float a = 10.0;
int b;
std::memcpy(std::addressof(b), std::addressof(a), size(b));
and does what you'd expect the union to do if you were a C programmer.