Qwerty
Qwerty

Reputation: 153

Copy a little count of bytes

How it is possible to write this more laconical but not using memcpy?

memcpy(pDest, pSrc, 4);

for (int i = 0; i < 4; i++)
   pDest[i] = pSrc[i]; 

Because calling memcpy is not optimal sometimes

Upvotes: 1

Views: 198

Answers (2)

user694733
user694733

Reputation: 16047

Here are excellent comments, but since nobody else has yet posted the most obvious answer:

Modern compilers are excellent at optimizing memcpy. It may inline it, or use different versions for different data.

Measure your code performance first and draw conclusions based on that. If memcpy seems to be the bottleneck on your code, you might want reconsider your algorithm.

By introducing your own alternatives to memcpy you will likely introduce bigger/slower code, or worse: unportable code which may break when least expected.

Upvotes: 3

john
john

Reputation: 88007

#include <cstdint>

*(uint32_t*)pDest = *(uint32_t*)pSrc;

Upvotes: 2

Related Questions