Memory cost [de] distribution and potential compiler optimization (C ++)

Is a certain memory allocation cost [de] determined? If the cost depends on the particular compiler used, is there a general way to allocate [de] memory so that I can reasonably assume the cost?

Can the compiler optimize the following code so that the "new" call is executed only once?

char * arr = NULL; for (size_t i = 0; i < 5000000000; ++i) { arr = new char[100000000] ... // Process things here delete []arr; } 
+6
source share
3 answers

The compiler will almost certainly not be able to perform this optimization. At the lowest level, memory allocation comes down to calls to library functions such as malloc (and one level deeper for the OS API). It is not safe for the compiler to assume that individual malloc/free pairs may be omitted, and their storage will be reused, because their implementation should be outside the scope of the optimizer.

Also, I don't think this is a good job for the optimizer. This is what you, a programmer, can do without much effort.

There are no standardized costs for allocating / freeing memory. As a rule, the allocation / release time can vary greatly (for example, it will take much longer if the user space heap implementation is forced to retrieve fresh pages from the OS kernel memory manager).

A reasonable rule of thumb is that small distributions are more likely to be faster than larger ones, and distributions should be slower than de-distributions.

+6
source

The compiler may have some tweaks to optimize a piece of code (which contains some bugs), but you will need to tell the compiler if you are optimized for speed or size. There is nothing in the standard talking about the degree of performance required.

I would refuse distribution and release because I do not want to rely on the compiler.

In addition, since there is no garbage collection in the standard C ++ language, your allocation and deallocation can damage fragmented memory (or slow down execution).

BTW, you compare the variable i, which is an integer, with the floating point number "5000000000.0". Pay attention to the decimal point. Good programming practice is to compare integers with integers and a floating point floating point.

0
source

The time to allocate char [100000000] is less than the time whit to set all elements to 0 (which the constructor should do anyway). And if your code writes to each cell, the distribution is much cheaper than anything else.

And I don’t think there is a compiler that makes this work and only calls the constructor.

0
source

Source: https://habr.com/ru/post/885670/


All Articles