Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cost of memory [de]allocation and potential compiler optimizations (c++)

Is the cost of memory [de]allocation specifically defined? If the cost depends upon the specific compiler being used, is there a general way memory [de]allocation is implemented such that I can reasonably assume the cost?

Is the compiler able to optimize the following code such that the call to 'new' is only done once?

char * arr = NULL;
for (size_t i = 0; i < 5000000000; ++i)
{
    arr = new char[100000000]
    ... // Process things here
    delete []arr;
}
like image 918
Chris Morris Avatar asked Apr 11 '11 18:04

Chris Morris


People also ask

How dynamic memory allocation can be achieved in C?

In C, dynamic memory is allocated from the heap using some standard library functions. The two key dynamic memory functions are malloc() and free(). The malloc() function takes a single parameter, which is the size of the requested memory area in bytes. It returns a pointer to the allocated memory.

Is malloc and free slow?

As time passes, the malloc and free functions get slower and slower because the block of appropriate size is more difficult to find.

How do I disable compiler optimization?

Use the command-line option -O0 (-[capital o][zero]) to disable optimization, and -S to get assembly file. Look here to see more gcc command-line options.

Is dynamic memory allocation slow?

Dynamic memory allocation and deallocation are very slow operations when compared to automatic memory allocation and deallocation. In other words, the heap is much slower than the stack.


1 Answers

The compiler is almost certainly not able to perform this optimization. At the lowest level, storage allocation boils down to calls to library functions such as malloc (and, one layer deeper, to OS APIs). For the compiler it's not safe to assume that individual malloc/free pairs can be left out and their storage reused because their implementation should be outside the optimizer's scope.

Apart from that, I don't think this is a good job for the optimizer. That's something that you, the programmer, can do without special efforts.

There is no standardized cost for memory allocation/deallocation. Generally, allocation/deallocation times may vary greatly (for example it will take significantly longer if the user-space heap implementation is forced to fetch fresh pages from the OS kernel's memory manager).

A reasonable rule of thumb is that small allocations are most likely faster than larger ones and allocations should be slower than de-allocations.

like image 104
Alexander Gessler Avatar answered Sep 29 '22 06:09

Alexander Gessler