View Single Post
  #12 (permalink)  
Old 08-09-2007, 03:41 AM
ramkumaraol ramkumaraol is offline
D-Web Programmer
 
Join Date: Jul 2007
Posts: 98
ramkumaraol is on a distinguished road
Default Re: Site Performance - Tips & Tricks

Pass objects and arrays using references in functions. Return objects and arrays as references where possible also. If this is a short script, and code maintenance is not an issue, you can consider using global variables to hold the objects or arrays.

References do not provide any performance benefits for strings, integers and other basic data types. For example, consider the following code:

function TestRef(&$a)
{
$b = $a;
$c = $a;
}
$one = 1;
ProcessArrayRef($one);

And the same code without references:

function TestNoRef($a)
{
$b = $a;
$c = $a;
}
$one = 1;
ProcessArrayNoRef($one);



PHP does not actually create duplicate variables when "pass by value" is used, but uses high speed reference counting internally. So in TestRef(), $b and $c take longer to set because the references have to be tracked, while in TestNoRef(), $b and $c just point to the original value of $a, and the reference counter is incremented. So TestNoRef() will execute faster than TestRef().

In contrast, functions that accept array and object parameters have a performance advantage when references are used. This is because arrays and objects do not use reference counting, so multiple copies of an array or object are created if "pass by value" is used. So the following code:

function ObjRef(&$o)
{
$a =$o->name;
}

is faster than:

$function ObjRef($o)
{
$a = $o->name;
}

Thanks,
Ramkumar.B

Last edited by ramkumaraol : 08-09-2007 at 03:46 AM.
Reply With Quote