I have a piece of code that is reading into a buffer of constant size, which can be simplified to basically
{ constexpr std::size_t buffer_size = 262144u; std::vector<char> buffer(buffer_size); // vector is reallocated every time read(buffer.data(), buffer.size()); // write into the buffer ... } For performance I was considering making the vector static to reduce re-allocating every time this function is called, something like this
{ constexpr std::size_t buffer_size = 262144u; static std::vector<char> buffer(buffer_size); // vector is allocated only once buffer.assign(buffer.size(), '\0'); // "reset" the vector contents read(buffer.data(), buffer.size()); // write into the buffer ... } I tried benchmarking these two methods and they appear to be nearly identical (for Clang with -O3) in terms of performance.
Is this linked benchmark a good test for the behavior I described?
Are one of these two methods "obviously" preferred over the other, from a performance perspective?
preferred over the other, from a performance perspective?from performance (and memory) perspective, i've seen projects using only global variables. But there are problems with global variables and don't forget rules of optimization. It's funny how, in your benchmark, doing thememset(buffer, '\0'part takes way longer time then callingmalloc. If you lower the buffer size in your benchmark, you'll see the difference. Still, in your benchmark, static vector is faster.readin my example) is a black-box 3rd party code, so I'm not sure what the exact requirements are. E.g. can it be full of arbitrary data, should it be "zeroed out", etc. I think that's a great point though, if I can skip writing to the whole buffer that should be a clear winner.buffer.assign()line, use the default constructor forvector, andreservethe space. Of course, don't callreadeither since the memory is allocated but not initialized, but your benchmark already doesn't involveread. This might tell you that the time to initialize the data dwarfs the time to allocate it.