Assume that one wants to make a copy of an array declared as
DATA_TYPE src[N];
Is memcpy
always as fast as or faster than the following code snippet, regardless of what DATA_TYPE
and the number of elements of the array are?
DATA_TYPE dest[N];
for (int i=0; i<N; i++)
dest[i] = src[i];
For a small type like char
and large N
we can be sure that memcpy
is faster (unless the compiler replaces the loop with a call to memcpy
). But what if the type is larger, like double
, and/or the number of array elements is small?
This question came to my mind when copying many arrays of double
s each with 3 elements.
I didn't find an answer to my question in the answer to the other question mentioned by wohlstad in the comments. The accepted answer in that question essentially says "leave it for the compiler to decide." That's not the sort of answer I'm looking for. The fact that a compiler can optimize memory copying by choosing one alternative is not an answer. Why and when is one alternative faster? Maybe compilers know the answer, but developers, including compiler developers, don't know!