In C++ I allocate memory using new. But if i need to reallocate it i have to allocate another block and copy. I tried using vector class for a reallocatable array but it seems slow. I need a simple reallocatable array with no additional functionality. Is it a good idea to use win api functions straight on? I mean HeapAlloc and HeapRealoc. Or is there another better way?
Posted on 2003-11-26 15:12:56 by Vaxon
the Heap functions work similar, they allocate a new block and copy old to new. I'm not sure, but I think the VirtualXX functions can reserve a large block of memory and lock (commit) the memory page by page.
Posted on 2003-11-28 17:09:26 by beaster
I tried heap functions - no gain in speed at all.
Posted on 2003-11-28 18:32:46 by Vaxon
There could be some gain in speed only if you reallocate the last array you allocated.
When you allocate some memory, and you get its ptr in EAX, the actual size of the array is stored in dword ptr. And it's the number of bytes you allocated + 4. Thus, the reallocation of the last buffer will probably take only time for modification of that .
I personally use my own allocation, with 4kB pages boundaries, that resizes the buffer only if it will reach over 4k. But I use this allocation with 7-byte objects, that get modified 20 times/second
Posted on 2003-11-29 01:38:11 by Ultrano

When you allocate some memory, and you get its ptr in EAX, the actual size of the array is stored in dword ptr. And it's the number of bytes you allocated + 4.

Hrm, where is this? Not on my win2k+sp4 with HeapAlloc. Don't depend on implementation-specific things :).

But it's true that HeapReAlloc will try to expand the current block if possible - if not, the alloc-new-block-and-copy-over will happen. This can happen with other blocks than just the most recently allocated one, though - the internals (and thus efficiency) varies from OS to OS, it seems that NT is somewhat more efficient. On XP/win2k3 or better, you can additionally specify that you want to use a Low-Fragmentation Heap model.

And in the case where the default heap strategy doesn't suit you - do like Ultrano and other people, and implement your own strategy atop HeapAlloc (large blocks) or VirtualAlloc. Be sure to use something better that a simple linked list, though, or you will probably end up with worse performance.
Posted on 2003-12-05 08:03:54 by f0dder