LunarEclipse
LunarEclipse

Reputation: 1011

Do ptr::copy::<u8>(src as *const u8, dst as *mut u8, size_of::<T>()) and ptr::copy::<T>(src, dst, 1) have the same performance?

Do these two calls have the same performance?

ptr::copy::<u8>(src as *const u8, dst as *mut u8, size_of::<T>());

ptr::copy::<T>(src, dst, 1);

src and dst are both type T raw pointers, there're two ways of copying src to dst. I don't know how does rust implement ptr::copy, so do they have the same performance?

Upvotes: 2

Views: 272

Answers (1)

Lukas Kalbertodt
Lukas Kalbertodt

Reputation: 88906

The two cases you mention will have the same performance. There is no reason to compile them differently. The optimizer can easily see that your *const u8 is actually coming from a *const T. And size_of::<T>() is also known at compile time.

The only way you could get worse performance is if your cast to *const u8 and the size_of call are too far away from your copy call. When the compiler cannot propagate this information about the pointer and size properly.

Check out the generated assembly in those three cases: https://godbolt.org/z/h4M44977P

In any case, there is no reason not to go with the simple ptr::copy(src, dst, 1) version. There is a reason that ptr::copy is generic over T: it makes code simpler and less error-prone.

Upvotes: 4

Related Questions