large string...

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
example code

function myfunc1()
    return myfunc2();

function myfunc2()
    return myfunc3();

function myfunc3()
    return very_large_string; // let's say that very large string is  30kb  
of data

print myfunc1();

The question is, would these 30Kb of data be copied into each function  
wasting resources or only reference to these data would be propagated to  
myfunc1? PHP version is 5.0.x

Best regards,

B.r.K.o.N.j.A = Bionic Robotic Knight Optimized for Nocturnal Judo and  

Re: large string...

Quoted text here. Click to load it

 PHP uses copy-on-write for the contents of variables. So, there'd only be one
copy of the large string in memory in the above.

 Whilst "=" assigns by copy, it's my understanding that it initially just sets
up references. But when it comes to writing to the new variable, it only then
does the copy, giving the same semantics as copy-by-value but giving savings
where the copies are actually just read-only.

 $a = 'long string';  // one instance of long string
 $b = $a;             // still one instance - $b and $a refer to same data
 $b .= 'some more';   // only at this point is the data copied, so that $b  
                      // can be modified

 More information here:

 In the case of functions, there's a further hint in the manual that multiple
copies may be avoided automatically:
 "Do not use return-by-reference to increase performance, the engine is smart
enough to optimize this on its own."

Andy Hassall :: :: :: disk and FTP usage analysis tool

Re: large string...

B.r.K.o.N.j.A wrote:

Quoted text here. Click to load it

Andy replied below so I will not repeat his answer but will only add  
that you can explicitly declare arguments to be accessed by reference, as in

function myfunct(&$foobar)

Also, global variables can be used to minimize stack manipulation.

Mladen Gogala

Re: large string...

Mladen Gogala wrote:
Quoted text here. Click to load it

It's worth noting that references tend to cause more data copying. When
a referenced variable is passed by value, copy-on-write occurs. When a
"copy" of a value is passed by value, it does not unless the function
called modifies its parameters.

Global variables used within functions are referenced in PHP 4, so the
same rules apply.

Site Timeline