Strings in Delphi locating in dynamic memory.
How to calculate actual memory (in bytes) used by string
variable?
I know the string must store some additional information, at least reference count and length, but how many bytes it uses except characters?
var
S: string;
Delphi 2010, XE, XE2 used
How much memory does a string take in Python? Adding single characters to a string adds only a byte to the size of the string itself, but every string takes up 40 bytes on its own.
For a default encoding, it will take 1 byte for a character. So Answer is 1 byte for default encoding.
To put it another way, Step 1: calculate the length of the address in bits (n bits) Step 2: calculate the number of memory locations 2^n(bits) Step 3: take the number of memory locations and multiply it by the Byte size of the memory cells.
The layout on 32 bit UNICODE DELPHI taken from official Embarcadero documentation is like this:
Note that there's an additional longint field in the 64 bit version for 16 byte alignment. The StrRec
record in 'system.pas' looks like this:
StrRec = packed record
{$IF defined(CPUX64)}
_Padding: LongInt; // Make 16 byte align for payload..
{$IFEND}
codePage: Word;
elemSize: Word;
refCnt: Longint;
length: Longint;
end;
The payload is always 2*(Length+1) in size. The overhead is 12 or 16 bytes, for 32 or 64 bit targets. Note that the actual memory block may be larger than needed as determined by the memory manager.
Finally, there has been much mis-information in this question. On 64 bit targets, strings are still indexed by 32 bit signed integers.
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