cppques...@googlemail.com wrote:
I just had the following idea for opertor new and delete
(I am sure I am not the first one, haven't seen it
so far though):
class A
{
std::vector< int> someData;
static std::stack used;
public:
static void * operator new (size_t size);
static void operator delete (void *p, size_t size);
};
void* A::operator new(size_t sz)
{
void* res;
if( used.size() > 0)
{
res = used.back();
used.pop();
return res;
}
return ::new( sz);
}
void A::operator delete (void *p, size_t sz)
{
someData.clear();
used.push( p);
}
If there are a lot of instances of A to be allocated and freed all the
time,
could (would) this result in a performance gain compared to
the standard new/delete operator as system calls are avoided in most
cases?
Of course it is obvious that there is a certain memory overhead (for
the stack and as all As are never freed), but it looks to me that this
is a very easy way to gain a lot of performance potentially. Am I
missing something?
The idea, as I understand it, is not to deallocate the last "freed"
instance[s] but to reuse it. Seems nice to have the freeing delayed,
and that's essentially what Boost's pooled memory manager does. Their
idea is not to deallocate and not to reuse, but instead just keep
giving you new pieces and deallocate them all at once at the end, when
you don't need any of them any more.
amount used. Some objects might have a very short life span, others