I’m making a C++ wrapper for a piece of C code that returns a large array, and so I’ve tried to return the data in a vector<unsigned char>.
Now the problem is, the data is on the order of megabytes, and vector unnecessarily initializes its storage, which essentially turns out to cut down my speed by half.
How do I prevent this?
Or, if it’s not possible — is there some other STL container that would avoid such needless work? Or must I end up making my own container?
(Pre-C++11)
Note:
I’m passing the vector as my output buffer. I’m not copying the data from elsewhere.
It’s something like:
vector<unsigned char> buf(size); // Why initialize??
GetMyDataFromC(&buf[0], buf.size());
For default and value initialization of structs with user-provided default constructors which don’t explicitly initialize anything, no initialization is performed on unsigned char members:
I think this is even legal under the strict aliasing rules.
When I compared the construction time for
vvs. avector<unsigned char>I got ~8 µs vs ~12 ms. More than 1000x faster. Compiler was clang 3.2 with libc++ and flags:-std=c++11 -Os -fcatch-undefined-behavior -ftrapv -pedantic -Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-missing-prototypesC++11 has a helper for uninitialized storage, std::aligned_storage. Though it requires a compile time size.
Here’s an added example, to compare total usage (times in nanoseconds):
VERSION=1 (
vector<unsigned char>):VERSION=2 (
vector<uninitialized_char>):I’m using clang svn-3.6.0 r218006