In the previous post test my records are also in a dynamic array which calls setlength() on each add. I'm just saying that 1 TObject in general with same variables takes more memory space than 1 record.
You can reduce the memory overhead of objects, by writing your own memory allocation for them and holding several in a single block of memory (similar to records in a dynamic array).
To understand one of the differences between object and records:
- objects are internally pointer
- records are not pointers
- (dynamic array are pointers, static arrays are not. But that does not matter for now)
var
AObj: TObject
ARec: record (* fields .... *) end;
Lets say:
- AObj (the actual variable) is locate in memory at 0x40000
Then it takes sizeof(Pointer) = 4 bytes (on 32 bit CPU) at that location.
Those 4 bytes point to 0x052100 where the actual data is located:
sum of SizeOf(all_fields)
+ some internal data, like pointer to class info (class info exists only ONCE for all objects of the class)
- ARec (the actual variable) is located at 0x040010
And it has all it's data right there
the above is also true, if your objects are in a dynamic array. The dynamic array, is an array of the pointers.
Since the obj has it's data at 0x052100, this memory had to be allocated. The heap mgr would have had to keep track of this allocation, and add some overhead (depends on which heap mgr you use). But usually at least the size of the memory (4 or 8 bytes / 32 or 64 bit CPU). And likely some other internal info. E.g allocating memory can fragment the amount of free memory. The heap mgr allocates big chunks from the os, and then divides them, but with fragmentation some of it can be lost.
So you can see: An object has an additional pointer (the actual variable) + pointer to class (since the actual class of your instance can be a sub-class of what the variable was declared as, so it must be stored in the data) + memory mgr overhead...
And maybe even more. I don't know.
Now if you allocate memory for your objects yourself, you can alocate a continues block of memory for 100 objects, saving 99 times the heap-mgr overhead.
(Don't ask me how to do. But it is possible. Be careful, as inherited classes need different amount of mem, making this extremely complex. I think you override GetInstance or something like that....)
Yet you get inheritance for this price...
P.s. accidentally modified by me(marcov) when I hit modify instead of quote. (stupid muscle memory). Restored the best I could