NYCPHP Meetup

NYPHP.org

[nycphp-talk] slow php

Hans Zaunere lists at zaunere.com
Mon Feb 16 22:37:30 EST 2009


> One note, please add at least the subject of the thread in when replying
to a
> section of a digest email and puleaze trim messages. 90% of your email had
> nothing to do with what you were asking. I won't even get into the top
posting
> issue....

Thanks David, this is something I've been meaning to mention.

For those on digest, or just in general, please trim your posts correctly
and if needed, set the subject line correctly.  Where possible, please avoid
HTML email as well.

> Now, by default PHP passes function arguments by value. That means it
makes a
> copy of what you specified as argument and works with that copy. That
means if
> you pass an array and change an element from within the function the array
is
> changed only within the scope of the function. In order to have the
original
> be changed as well you can either return the changed array and then assign
it
> to the original. The more convenient way is to pass the array by
reference,
> because then the function will not make a copy and apply changes to the
> original.

Just to reiterate some things already mentioned...

If you don't pass by reference (not using the & in the function prototype)
the original value will not be changed.  However, if the function doesn't
change the passed-in variable in any way, PHP shouldn't copy the data it
contains, and thus you won't be using extra memory.

If you do change the variable within the function, PHP institutes
copy-on-write, and thus it'll copy the contents of the variable before
making the modification, and you'll use extra memory.  The original value
will be unchanged.

If you use the ampersand (&) in the function prototype, then you're passing
a reference that refers to the original value.  This means that if the
function modifies the value, the original value that's passed into the
function is also modified.  This doesn't involve a copy of the original
value.

It should be noted that passing by reference (using the ampersand) is
slightly more expensive than passing variables directly - assuming you don't
change the variable in a different scope.  Thus, if you know it won't be
change within the function, you shouldn't use the ampersand in the
function's definition.

This does not apply to objects, which are always passed by reference.  That
is, an object passed into a function, and then modified within the function,
will always modify the original object (you need to clone it otherwise).

Please note that this all applies to PHP 5 only.  PHP 4 is anyone's guess
(and hopefully a long forgotten guess :)  And frankly, this is all
last-understood stuff - any updates to current behavior, or better yet PHP 6
expected behavior, would be welcomed.  Perhaps it's time for another
presentation on this topic?

H





More information about the talk mailing list