string - Why Does SetString Take Less Memory in Delphi (with Unicode)? -


This is Delphi 2009, so the Unicode applies.

I had some code that saw the strings see buffer in the string list as follows:

  var buffer: TBites; RecStart, RecEnd: PCHar; S: string; FileStream.Read (buffer [0], size); Repeat ... retrieve the next record and rewrite that point in buffer; Setstring (S, Ricastart, Recend - Richest); MyStringList.Add (s); By the end of the buffer  

But during some modifications, I changed my argument, so that I had to add the same record, but not as a string separately and through the setstring, i.e.

  var SRecord: string; Repeat SRecord: = ''; Repeat SRecord: = SRecord + ... processed by line buffer; Buffer to MyStringList.Add (SRecord) until the end of the record; By the end of the buffer  

The memory usage of the stringlist I saw went from 52 MB to about 70 MB. This was an increase of more than 30%

Repeated SRecord:

To get back to my low memory usage, I came to know that I used setstring to create string variables Was, as my stringlist adds: ''; Repeat SRecord: = SRecord + ... processed by line buffer; By the end of the record in buffereststring (S., PCR (SRecord), length (SRecord)); MyStringList.Add (s); By the end of the buffer

Check and compare the S and SharkCard, they are exactly the same in all cases but adding the Astercod to MyStringList adds more memory than adding S.

Does anyone know what's going on and why the setstring saves memory?


The follow-up I did not think it would be, but I just checked it to make sure.

Neither:

  SetLength (SRecord, length (SRecord));  

and neither

  trim (SRecord);  

Issues additional space SetString is required to do this.

If you add strings, then memory manager will allocate more memory because it assumes that you Add more and more text and allocate additional space for future insertions. In this way the allocation size of the string is much greater than the size used (based on the used memory manager). If you use setstring, the allocation size of the new string is almost the same as the used size. And when the SRecord string goes out of the scope and its reg count-zero becomes zero, then the memory captured by SRecord continues. So you end up with the smallest necessary allocation size for your string.


Comments