Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocating memory inside loop vs outside loop

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;
like image 949
Aamir Avatar asked Oct 12 '25 14:10

Aamir


1 Answers

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];
like image 153
C Johnson Avatar answered Oct 15 '25 08:10

C Johnson