[fpc-pascal] PChar & AnsiString

David Emerson dle3ab at angelbase.com
Tue Jun 1 21:21:38 CEST 2010


> > >> This is not correct. Many strings are simply referenced several  
> > >> times.
> > >
> > > May I ask in which typical cases?

In an earlier version of our database (before we had things properly typed) many 
things were stored as strings. Thus a common ansistring may have had a 
reference count in the hundreds or even thousands. Most of the time, if I 
changed one of them, I would not want to change them all! But it saved a lot of 
memory to not be redundantly storing the same string.

> > The most common one is probably assigning a function result to a  
> > variable or field.
> 
> Is there increment of ref count (I think it does +1-1)? If no, passing the ref
> cannot have any side-effect, so the copy_on_write scheme does not apply -- or
> rather does not make any change if applied. This is plain reference copy.
> The issue is rather for parameter passing, since here the original var
> survives the call (see Martin's post). 

I believe it depends on the circumstance. It's been a while since I tested this, 
but IIRC, when a variable is passed-by-value the ref count is incremented, 
whereas if it is passed-by-reference the ref count is not incremented... as one 
should hope. In the case of the latter, this means that if the ref count is 
one, then copy-on-write is not needed, as there is only the one instance of the 
string-- so that can save some processor time. Back when I was dealing with 
enormous ansistrings that were frequently being changed, I spent considerable 
time researching this so as to figure out how to avoid unnecessary 
copy-on-writes. What I found is that the compiler's treatment of them is quite 
intuitive: there were no unpleasant surprises. I ended up changing a number of 
functions which took a value parameter and returned a result to instead take a 
reference parameter and change that.

Have fun...
~David.




More information about the fpc-pascal mailing list