I think a memory pool would make a difference in some situations. Since boost::object_pool<>
doesn't provide a method to allocate a array of objects, so I would use boost::pool<>
which is actually the underlying memory pool of boost::object_pool<>
.
#include <cstdio>
#include <ctime>
#include "boost/pool/pool.hpp"
struct Letter{
float a, b, c;
int *p;
};
class Label
{
public:
Label() : m_myArray(NULL), string_length(1), last_size(0){}
void set_size(size_t n)
{
last_size = string_length; // use last_size to store the number of last allocation, just for test.
string_length = n;
}
void ParseText()
{
delete[] m_myArray;
m_myArray = new Letter[string_length];
}
void ParseText_pool();
private:
Letter* m_myArray;
size_t string_length;
size_t last_size; //boost::pool<>::ordered_free need the size
};
boost::pool<> p(sizeof(Letter));
void Label::ParseText_pool()
{
if(m_myArray)
p.ordered_free(m_myArray, last_size); // ordered_free need the right size
m_myArray = (Letter*)p.ordered_malloc(string_length); // if you need call the ctor, use placement new.
}
int main()
{
Label l;
float startTime = (float)clock()/CLOCKS_PER_SEC;
for(int i = 1; i < 1000000; ++i)
{
l.set_size(i%100 + 1);
l.ParseText();
}
float endTime = (float)clock()/CLOCKS_PER_SEC;
printf("without pool, time: %f\n", endTime - startTime);
Label l2;
startTime = (float)clock()/CLOCKS_PER_SEC;
for(int i = 1; i < 1000000; ++i)
{
l.set_size(i%100 + 1);
l2.ParseText_pool();
}
endTime = (float)clock()/CLOCKS_PER_SEC;
printf("with pool, time: %f\n", endTime - startTime);
};
Run on my machine and coliru, it shows the more frequent the allocation, the greater the advantage of using a memory pool.