Delphi String Sharing Question
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 开发者_C百科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!
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.
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.
精彩评论