开发者

Efficiency of std::copy vs memcpy [duplicate]

This question already has answers here: Is it better to use std::memcpy() or 开发者_运维知识库std::copy() in terms to performance? (8 answers) Closed 7 years ago.

How severe is the efficiency loss between using memcpy and std::copy?

I have a situation where the vector implementation on my system doesn't appear to use contiguous memory, which is making me have to std::copy its contents later on rather than doing memcpy(dest, &vec[0], size);. I'm not sure how badly this is likely to impact efficiency.


A reasonably decent implementation will have std::copy compile to a call memmove in the situations where this is possible (i.e. the element type is a POD).

If your implementation doesn't have contiguous storage (the C++03 standard requires it), memmove might be faster than std::copy, but probably not too much. I would start worrying only when you have measurements to show it is indeed an issue.


While you've gotten a number of good answers, I feel obliged to add one more point: even if the code is theoretically less efficient, it's rarely likely to make any real difference.

The reason is pretty simple: the CPU is a lot faster than memory in any case. Even relatively crappy code will still easily saturate the bandwidth between the CPU and memory. Even if the data involved is in the cache, the same generally remains true -- and (again) even with crappy code, the move is going to be done far too quickly to care anyway.

Quite a few CPUs (e.g., Intel x86) have a special path in the hardware that will be used for most moves in any case, so there will often be literally no difference in speed between implementations that appear quite a bit different even at the assembly code level.

Ultimately, if you care about the speed of moving things around in memory, you should worry more about eliminating that than making it faster.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜