为什么SetString在Delphi中使用较少的内存(使用Unicode)?
这是Delphi 2009,因此Unicode适用。
我有一些代码将缓冲区中的字符串加载到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的内存使用从52 MB上升到大约70 MB。这增加了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));
也不
Trim(SRecord);
释放多余的空间。似乎需要SetString这样做。
没有找到相关结果
已邀请:
2 个回复
车料
脖呐