Delphi字符串共享问题
我有大量对象,其中都存储有文件名。所有文件名都位于给定的基本目录中(我们称之为C:\BaseDir\
)。我现在正在考虑两种替代方案:
- 在对象中存储绝对路径
- 在对象中存储相对路径并另外存储基本路径
如果我正确理解 Delphi 字符串,则第二种方法将需要更少的内存,因为基本路径字符串是共享的 - 鉴于我将相同的字符串字段传递给所有对象,如下所示:
TDataObject.Create (FBasePath, RelFileName);
这个假设正确吗?内存中是否只有一个基本路径的字符串实例?
如果有人知道处理此类情况的更好方法,也请随时发表评论。
谢谢!
I have a large amout of objects that all have a filename stored inside. All file names are within a given base directory (let's call it C:\BaseDir\
). I am now considering two alternatives:
- Store absolute paths in the objects
- Store relative paths in the object and store the base path additionally
If I understand Delphi strings correctly the second approach will need much less memory because the base path string is shared - given that I pass the same string field to all the objects like this:
TDataObject.Create (FBasePath, RelFileName);
Is that assumption true? Will there be only one string instance of the base path in memory?
If anybody knows a better way to handle situations like this, feel free to comment on that as well.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你是对的。当您使用两个字符串变量编写 s1 := s2 时,内存中有一个字符串具有(至少两个)对其的引用。
您还询问尝试减少内存中的字符串数量是否是一个好主意。这取决于与其他消耗内存的对象相比您有多少字符串。只有你才能真正回答这个问题。
You are correct. When you write s1 := s2 with two string variables, there is one string in memory with (at least two) references to it.
You also ask whether trying to reduce the number of strings in memory is a good idea. That depends on how many strings you have in comparison to other memory consuming objects. Only you can really answer that.
正如 David 所说,公共字符串将被共享(除非您使用 ie UniqueString())。
话虽如此,这看起来像是过早的优化。如果您实际上需要使用完整路径并且从不需要单独的目录和文件名部分,那么您应该仅在真正遇到内存问题时才考虑将它们分开。
不断连接基本部分和文件名部分可能会显着减慢程序速度并导致内存碎片。
As David said, the common string would be shared (unless you use ie UniqueString()).
Having said that, it looks like premature optimisation. If you actually need to work with full paths and never need the dir and filename part separately then you should think about splitting them up only when you really run into memory problems.
Constantly concatenating the base and filename parts could significantly slow down your program and cause memory fragmentation.