这是Delphi 2009,因此适用Unicode。
我有一些代码,它将字符串从缓冲区加载到StringList中,如下所示:
检查和比较S和SRecord,它们在所有情况下都完全相同。但是将SRecord添加到MyStringList中所使用的内存比添加S要多得多。
有人知道发生了什么以及为什么SetString可以节省内存吗?
跟进。我没想到会这样,但我检查了一下,确保没有。
释放多余的空间。似乎需要使用SetString来完成此操作。
我有一些代码,它将字符串从缓冲区加载到StringList中,如下所示:
var Buffer: TBytes; RecStart, RecEnd: PChar; S: string;
FileStream.Read(Buffer[0], Size);
repeat
... find next record RecStart and RecEnd that point into the buffer;
SetString(S, RecStart, RecEnd - RecStart);
MyStringList.Add(S);
until end of buffer
但在进行一些修改时,我更改了我的逻辑,结果我添加了相同的记录,但是它们是作为单独派生的字符串添加的,而不是通过SetString添加的,例如:
var SRecord: string;
repeat
SRecord := '';
repeat
SRecord := SRecord + ... processed line from the buffer;
until end of record in the buffer
MyStringList.Add(SRecord);
until end of buffer
我注意到StringList的内存使用从52MB增加到了约70MB,增加了超过30%。
为了恢复低内存使用率,我发现必须使用SetString创建字符串变量并将其添加到StringList中,如下所示:
repeat
SRecord := '';
repeat
SRecord := SRecord + ... processed line from the buffer;
until end of record in the buffer
SetString(S, PChar(SRecord), length(SRecord));
MyStringList.Add(S);
until end of buffer
检查和比较S和SRecord,它们在所有情况下都完全相同。但是将SRecord添加到MyStringList中所使用的内存比添加S要多得多。
有人知道发生了什么以及为什么SetString可以节省内存吗?
跟进。我没想到会这样,但我检查了一下,确保没有。
SetLength(SRecord, length(SRecord));
nor
Trim(SRecord);
释放多余的空间。似乎需要使用SetString来完成此操作。