Re: better new delete
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):
std::vector< int> someData;
static std::stack used;
static void * operator new (size_t size);
static void operator delete (void *p, size_t size);
void* A::operator new(size_t sz)
if( used.size() > 0)
res = used.back();
return ::new( sz);
void A::operator delete (void *p, size_t sz)
If there are a lot of instances of A to be allocated and freed all the
could (would) this result in a performance gain compared to
the standard new/delete operator as system calls are avoided in most
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
The general idea is called a free-list or, with more sophisticated
management, a cache. And what you're missing is, first, that std::stack
itself uses dynamic allocation, and second, that in operator delete you
don't have access to instance member data (the instance has already been
destroyed), and third, that a free-list is based on a certain usage
pattern (otherwise it just adds overhead), and fourth, that defining
operator new and operator delete is very costly in that it prohibits
other possibly more important usages of that mechanism, and fifth, that
it's generally not a good idea to do micro-optimization. In short don't
do it, or at least, don't do it yet (for optimization, first measure!).
Cheers, & hth.,
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
Q: What is the most annoying thing on usenet and in e-mail?