Re: heap fragmentation & operator new

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Andrew Haley wrote:
It gives performance advantage over what, exactly?
Using malloc/realloc/free gives a performance advantage over new/delete
since realloc need not move the block if it can resize inplace. For example:

double *d=static_cast<double *>(malloc(1000*sizeof(double)));
d=static_cast<double *>(realloc(500*sizeof(double)));

the block pointed to by d does not need to be moved and the 500 doubles
that are freed are available on the heap. But to do the same with new,

double *d=new double[1000];
double *tmp=new double[500];
memcpy(tmp,d,500*sizeof(double));
delete [] d;
d=tmp;

With new you always have to move the block, if you don't explicitly move
when shrinking, the bytes you no longer need are not available for the
heap to use. In both cases the same goes for extending the length of the
array. Apparently when using new/delete the heap can become more
fragmented than when using malloc/realloc/free, and lead to user running
out of memory sooner.

I was exploring the new/delete avenue because it would seem cleaner to
me to stick with C++ mechanism in a C++ code, and we'd get the benefit
of bad_alloc exceptions. However, given that new is using malloc under
the hood(at least by g++) I suppose using malloc/realloc/free is a non
issue. Thanks for the feedback.

Burlen



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux