In Delphi, you can get the size of a value type with the sizeof()
compiler magic function, but calling sizeof()
on a reference type will give you the size of a pointer, not of the value it's pointing to.
For objects, you can get the memory size with the InstanceSize
method, but what about for dynamic arrays? Due to padding, length(MyArray) * sizeof(element)
may not be accurate. So, is there any accurate way to get the memory size of a dynamic array?
We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);
The memory allocation for an array includes the header object of 12 bytes plus the number of elements multiplied by the size of the data type that will be stored and padding as needed for the memory block to be a multiple of 8 bytes.
What is a Dynamic Array? A dynamic array is quite similar to a regular array, but its size is modifiable during program runtime. DynamArray elements occupy a contiguous block of memory. Once an array has been created, its size cannot be changed.
The elements of the dynamic array are stored contiguously at the start of the underlying array, and the remaining positions towards the end of the underlying array are reserved, or unused.
Between elements of a dynamic array there is no padding, Length(MyArray)*SizeOf(Element)
should be accurate.
In fact, length(MyArray) * sizeof(element)
will be accurate for the array content excluding any internal dynamic array or string.
If you want the whole array used memory, including nested reference types content size, you can use our TDynArray
wrapper. It is able to serialize into binary any dynamic array, including reference counted members (like dynamic arrays or strings). You have SaveTo
/ SaveToStream
methods for this purpose, and you are able to get the actual size of all content.
Take a look at this blog article, which presents this wrapper. It is open source, and works from Delphi 5 up to XE4, in both Win32 and Win64 platform.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With