Page 1 of 1

returning strings VS by reference

Posted: Sun Dec 31, 2006 3:51 pm
by alex.barylski
I have a function which returns large blobs of HTML and I just switched it to return by reference via a parameter just for a cleaner looking invocation...

Code: Select all

$o->blah('Test', $buff); // Prefered...
VS

Code: Select all

$buff = $o->blah('test');
I just profiled the two numerous times and apparently there is little difference so I assume PHP5 returns all strings by reference already??? I know objects, etc are by default reference in PHP5...but what about when returning via return???

Anybody have a link or can U confirm my suspicions?

Cheers :)

Posted: Sun Dec 31, 2006 4:12 pm
by RobertGonzalez
I think there is mention of PHP 5 reference handling in the manual, I just don't have the time to search the manual right now. But I know it is there.

Posted: Sun Dec 31, 2006 4:24 pm
by alex.barylski
Yea I know....I could sift through the docs...which I have in the past...but I don't remember any mention of return values just function arguments...

I'll take a quick peak again :)

Thanks :)

Edit: Found it

http://ca3.php.net/manual/en/language.r ... return.php

Posted: Sun Dec 31, 2006 8:46 pm
by timvw
If i'm not mistaken they've choosen to store a string only once.. So it's perfectly possible that a couple of variables point to the same memory (that holds the string). So instead of passing the actual string i would presume that they only pass the address...

Btw, i think that your example would make more sense if you showed the signature (with the &).. since calling such a function is exactly the same as calling one without references...

Posted: Mon Jan 01, 2007 6:54 am
by Ollie Saunders
timvw wrote:If i'm not mistaken they've choosen to store a string only once.. So it's perfectly possible that a couple of variables point to the same memory (that holds the string). So instead of passing the actual string i would presume that they only pass the address..
Yeah, I'm pretty sure that is what happens. The Zend engine avoids physically moving data around whenever it can send addresses. I'm pretty sure this will even be done with integers and floats as well because the zval (is that right?) is always a larger object than a memory address.

Posted: Mon Jan 01, 2007 10:08 am
by Chris Corbyn
PHP is copy-on-write. It will never make a new copy of a variable in memory, right up until the point you modify it. So when you return the value it's the same location in memory, but if you then concatenate to it or some other operation, you'll see memory shoot up.