Friday, May 23, 2008

c++: reuse memory for objects

It happens when you are creating and deleting objects heavily. Like this:

    for (int i=0;i<1000000;++i)
    {   
        A *a = new A;

        //do something with 'a'

        delete a;
    }
Yup, it happens and sometimes it's a best solution. If you can't use stack memory because A is pretty big and you used almost all of the stack memory before or used a recursion. But this is extremely slow. You obtain memory fragmentation and invoke memory manager to get free chunk of memory and than free it. c++ specification allows you to reuse memory:
#include <new>

int
main(int argc, char **argv)
{
    char *memory = new char[sizeof(A)];
    void *place = memory;
    
    for (int i=0;i<1000000;++i)
    {
        A *a = new(place) A;

        //do something with 'a'

        a->~A();
    }   
}
In the code sample above A in the loop is always put into the 'memory'. The executable will request for the chunk of memory once before the loop. Depending on the code this may be more than 10 times faster. While using new() developer have to call destructor explicitly and include 'new' header manually. Anyway, if you can put A in the loop into the stack, try to do it. It the fastest and the safest way:
    for (int i=0;i<1000000;++i)
    {   
        A a;

        //do something with 'a'
    }   

No comments: