Is there noticeable performance penalty for allocating LARGE chunks of heap memory in every iteration of loop? Of course I free it at the end of each iteration.
An alternative would be to allocate once before entering the loop, repeatedly using it in all iterations, and eventually freeing it up after exiting the loop. See the code below.
// allocation inside loop
for(int i = 0; i < iter_count; i++) {
float *array = new float[size]();
do_something(array);
delete []array;
}
// allocation outside loop
float *array = new float[size]();
for(int i = 0; i < iter_count; i++) {
do_something(array);
}
delete []array;
I would never do it inside the loop. Allocating memory is not a free event, and doing it once is definitely preferred over doing it over and over again. Also you can just allocate the array without the parenthesis, and you should be fine:
float *array = new float[size];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With