develooper Front page | perl.perl6.internals | Postings from July 2002

Re: Parrot Glossary - COW

Thread Previous | Thread Next
Nicholas Clark
July 5, 2002 07:16
Re: Parrot Glossary - COW
Message ID:
On Fri, Jul 05, 2002 at 02:54:18PM +0200, Aldo Calpini wrote:

> COW stands for Copy On Write. it means that when you have to copy a string,
> the "real" string to be copied (eg. its content, eg. the bytes) is not
> really copied in memory with the copy operation.
> rather, the new string is marked as COW, and it still points to the original
> string. when you read that string, you are "redirected" to the original
> one.

Both strings are marked (in some way) as being COW

> but when you want to write something to the string (eg. modify it), then
> the system notes the COW flag and performs the actual copying of bytes
> (possibly a part of them, if you are modifying only part of the string).

So that if you want to write something to either, the system notes the COW
flag, and performs the actual copy then.

> this approach saves memory, because you can create as many copies of a
> string as you want, without allocating it many times. unless you modify
> them, at least. it's also usually a great speed boost, because copying a
> string is performed in O(1) time, instead of O(n) - where n is the size of
> the string.

I suspect that the speed boost is going to be more noticeable for most
applications than the memory saving. It doesn't matter if I'm wrong on this :-)

If you're able to have

$a = "Imagine this is a stack frame of about 2K";
$b = $a;
undef $a;

and you don't have to actually do any copying of that 2K stack frame.
The same buffer just passes from $a to $b without copying, as long as the
code marked ... doesn't touch $a or $b.

And if the code marked ... does alter $a or $b, the internals spot the COW
flag and do the copy, as if it had happened for real at the point where
$b = $a; was run.

Nicholas Clark

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About