Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much memory was actually allocated from heap for an object?

I have a program that uses way too much memory for allocating numerous small objects on heap. So I would like to investigate into ways to optimize it. The program is compiled with Visual C++ 7.

Is there a way to determine how much memory is actually allocated for a given object? I mean when I call new the heap allocates not less than the necessary amount. How can I find how much exactly has been allocated?

like image 997
sharptooth Avatar asked Dec 02 '22 08:12

sharptooth


2 Answers

There is no exact answer, because some heap managers may use different amount of memory for sequential allocations of the same size. Also, there is (usually) no direct way to measure number of bytes the particular allocation took.

You can approximate this value by allocating a certain number of items of the same size (say, 4096) and noting the difference in memory used. Dividing the later by the former would give you the answer. Please note that this value changes from OS to OS, and from OS version to OS version and sometimes Debug builds of your application may enable extra heap tracking, which increases the overhead. On some OSes users can change heap policies (i.e. use one heap allocator vs. another as default). Example: Windows and pageheap.exe

Just FYI, the default (not LFH) heap on Windows 32-bit takes up:

  • sizeof(your_type), rounded up to DWORD boundary,
  • 3 pointers for prev/next/size
  • 2 pointers for security cookies
like image 84
Rom Avatar answered Dec 20 '22 13:12

Rom


You're probably looking to move to a memory pool model (which is what the previous answer about "allocating a large pool" was describing. Because memory pools do not require overhead for each allocation, they offer space savings for large numbers of small objects. If the lifetime of a group of those small objects is short (i.e. you allocate a bunch of small objects then need to get rid of the lot), a memory pool is also much faster because you can just free the pool instead of each object.

Wikipedia has some info on the technique as well as a link to a few implementations:

http://en.wikipedia.org/wiki/Memory_pool

you should be able to find other implementations with a simple web search.

like image 37
James F Avatar answered Dec 20 '22 13:12

James F