Re: Passing strings efficiently

Joachim Durchholz <>
14 Mar 2003 11:20:03 -0500

          From comp.compilers

Related articles
Passing strings efficiently (2003-03-09)
Re: Passing strings efficiently (Joachim Durchholz) (2003-03-14)
Re: Passing strings efficiently (Martin Ward) (2003-03-14)
| List of all articles for this month |

From: Joachim Durchholz <>
Newsgroups: comp.compilers
Date: 14 Mar 2003 11:20:03 -0500
Organization: Compilers Central
References: 03-03-037
Keywords: storage, design
Posted-Date: 14 Mar 2003 11:20:03 EST

Ed Davis wrote:
> However, I was thinking that I could just pass the address of a
> special string structure, with some flags to indicate that it is
> read-only. Then, I would only have to make a copy of the string if
> foo() actually modified it. Of course, I'd have to be careful to free
> the copy when foo() completes.
> [I think you're reinventing garbage collection. -John]

No, it's not garbage collection, it's copy-on-write.

I know of three approaches for this:

Approach 1 is a "read-only" flag. Modifying a string involves making a
copy. You need garbage collection to get rid of the read-only strings,
so this might not be an option for you.

Approach 2 is a reference counting scheme. Modifying a string with
reference count 1 requires no special precautions, modifying one with a
count > 1 requires making a copy, redirecting the reference in question
to that copy (decreasing the reference count of the original by 1 and
increasing the copy's count to 1), and applying the change.
(Hope this was clear enough to follow...)
Like with all reference-counting schemes, you need to make sure that the
reference counts get decreased whenever a reference to the string goes
out of scope.

Approach 3 is not to have any modifiable strings. Any change always
creates a copy. Originals are garbage collected.
This sounds bad performance-wise, but knowing that the strings cannot
change offers various algorithmic optimization opportunities.
For this to work well, you almost definitely need automatic garbage
collection :-)


Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.