Sayantan Ghosh Sayantan Ghosh - 3 months ago 17
C++ Question

array allocation followed by memcpy or vector with reserve?

I have a byte array which i want to compress.(Size 400 byte on avg).I have two options.I keep an array of 400 byte and stuff bits in it.Finally say the compressed size is 300 byte so I use memcpy to copy those bytes to an array of size 300 and send.
Else I can keep a vector and reserve 400 byte and use push_back.(Here i can avoid the memcpy).
I get a huge number of arrays per second. So in a performance critical scenario which choice will give better performance?

Answer

If it needs to be fast, you definitely don't want to push_back each individual byte one-at-a-time; you want to do a bulk transfer, like what memcpy does. But you can use std::copy, which should be just as efficient. For primitive types like char or int, using std::vector with std::copy is basically a layer on top of a raw array and memcpy.

Comments