Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  1. Store absolute paths in the objects
  2. 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!

like image 681
jpfollenius Avatar asked Feb 23 '23 04:02

jpfollenius


2 Answers

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.

like image 91
David Heffernan Avatar answered Mar 04 '23 20:03

David Heffernan


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.

like image 37
ain Avatar answered Mar 04 '23 20:03

ain