I want to use a vector with the custom allocator below, in which construct()
and destroy()
have an empty body:
struct MyAllocator : public std::allocator<char> {
typedef allocator<char> Alloc;
//void destroy(Alloc::pointer p) {} // pre-c+11
//void construct(Alloc::pointer p, Alloc::const_reference val) {} // pre-c++11
template< class U > void destroy(U* p) {}
template< class U, class... Args > void construct(U* p, Args&&... args) {}
template<typename U> struct rebind {typedef MyAllocator other;};
};
Now for the reasons I have specified in another question, the vector
has to be resized several times in a loop. To simplify my tests on performance, I made a very simple loop like the following:
std::vector<char, MyAllocator> v;
v.reserve(1000000); // or more. Make sure there is always enough allocated memory
while (true) {
v.resize(1000000);
// sleep for 10 ms
v.clear(); // or v.resize(0);
};
I noticed that changing the size that way the CPU consumption increases from 30% to 80%, despite the allocator has empty construct()
and destroy()
member functions. I would have expected a very minimal impact or no impact at all (with optimization enabled) on performance because of that. How is that consumption increment possible? A second question is: why when reading the memory after any resize, I see that the value of each char in the resized memory is 0 (I would expect some non-zero values, since constuct()
does nothing) ?
My environment is g++4.7.0 , -O3 level optimization enabled. PC Intel dual core, 4GB of free memory. Apparently calls to construct
could not be optimized out at all?