Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate actual memory used by string variable?

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

like image 932
Andrew Avatar asked Jun 06 '12 08:06

Andrew


People also ask

How much memory is allocated for a string variable?

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.

How much memory does a character in a string take?

For a default encoding, it will take 1 byte for a character. So Answer is 1 byte for default encoding.

How is data memory calculated?

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.


1 Answers

The layout on 32 bit UNICODE DELPHI taken from official Embarcadero documentation is like this:

UNICODE DELPHI

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.

like image 184
opc0de Avatar answered Nov 02 '22 09:11

opc0de