这是德尔福2009年,所以统一适用。为什么SetString在Delphi中使用更少的内存(使用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似乎需要这样做。
顺便说一句,这是我在StackOverflow上100问题。我只想感谢编程界在过去的两年中为我解决我的编程问题提供了巨大的帮助。 – lkessler 2010-09-25 19:43:46