NYCPHP Meetup

NYPHP.org

[nycphp-talk] Re: Copy-on-write

George Webb gw.nyphp at gwprogramming.com
Fri Oct 31 15:12:14 EST 2003


Hi.  I hope I'm not the only one who finds this discussion
enlightening!


Analysis & Solutions <danielc at analysisandsolutions.com> wrote:
> Most functions return static values.  You can put that value into a
> variable.  If you alter that variable, you're altering THAT value.  I
> don't think PHP's going to be making a copy because there's no need to
> remember the old value returned by the function.


	So what if you call a function that generates a large
data result, e.g.:

function GetStuff () {
	$r = array();
	for ( $i=0; $i<100000; $i++ ) {
		$r[$i] = LookUpStuff ( $i );
	}
	return $r;
}
$myStuff = GetStuff();

	Then does this large data set actually get duplicated
twice?  E.g. if $r takes up 5 MB of space, then does $myStuff
take up *another* 5 MB of space?  According to conventional notions
of "return by value" it does.  But Dan is suggesting that PHP
optimizes this situation by silently changing the $myStuff assignment
to "return-by-reference" since $r is legitimately trashed after
the function returns, PHP can simply substitute the actual contents
of $r for $myStuff -- thereby re-using $r rather than creating a
fresh one and trashing the old one.

	I had been assuming that if the variable the function was
returning (in this case, $r) was sufficiently large, it would be
more efficient to return a *reference* to that variable, rather
than copying that huge thing.  So in that case the function would
have to be called as $myStuff =& GetStuff();  or defined as
function &GetStuff () { ... } .

	Then, in general, whenever you copy large variables, do
the same concepts apply?  For example, if $myArray is 5 MB, how
much space does the following function use???:

function TakeUpSpace () {
	$myArray = GetHugeArray(); // array data size will be 5 MB
	$myArray2 = $myArray; // take up more space ?
	$myArray3 = $myArray; //  "   "   "     "
	$myArray4 = $myArray; //  "   "   "     "
	$myArray5 = $myArray; //  "   "   "     "
	// now how much space have we used???
	return $myArray;
}

	Does this function actually require 25 MB of space?  Or,
since nothing is actually written to $myArray2 thru $myArray5,
these variables are not actually copied?


Regards, George.

George Webb
gw.nyphp at gwprogramming.com



More information about the talk mailing list