Efficiency of std :: copy vs memcpy

How serious is the performance loss between using memcpy and std::copy ?

I have a situation where the vector implementation in my system does not use continuous memory, which is why I have to std :: copy its contents later, and not memcpy(dest, &vec[0], size); . I'm not sure how much this can affect performance.

+6
source share
3 answers

A fairly decent implementation would be std::copy compile a memmove call in situations where this is possible (i.e., the element type is POD).

If your implementation does not have continuous storage (this requires the C ++ 03 standard), memmove may be faster than std::copy , but probably not too much. I would start to worry only when you have measurements to show that this is really a problem.

+13
source

As long as you have a number of good answers, I feel obligated to add another point: even if the code is theoretically less efficient, it rarely can have any real meaning.

The reason is quite simple: in any case, the processor is much faster than memory. Even pretty cheesy code will still easily saturate the bandwidth between the processor and memory. Even if the data is related to the cache, it still remains unchanged - and (again) even with crap code, the movement will be done too quickly to take care anyway.

Quite a few processors (for example, Intel x86) have a special hardware path that will be used for most moves anyway, so often there will be no difference in speed between implementations that seem quite different at the assembly code level.

Ultimately, if you care about the speed of things moving in memory, you should worry more about eliminating this than speeding it up.

+13
source

std::copy will use memcpy when appropriate, so you should just use std::copy and let it do the job for you.

+6
source

Source: https://habr.com/ru/post/896505/


All Articles