[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

No subject


Do References Speed Your Code?

References do not provide any performance benefits for non-object=
 variables. For example, consider the following code:

function TestRef(&$a)
    $b =3D $a;
    $c =3D $a;
$one =3D 1;

And the same code without references:

function TestNoRef($a)
    $b =3D $a;
    $c =3D $a;
$one =3D 1;

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 object parameters have a performance=
 advantage when references are used. This is because objects do not use=
 reference counting, so multiple copies of an object are created if "pass=
 by value" is used. So the following code:

function ObjRef(&$o)
   $a =3D$o->name;

is faster than:

$function ObjRef($o)
  $a =3D $o->name;

Note: In PHP 5, all objects are passed by reference automatically, without=
 the need of an explicit & in the parameter list.


- kasper
-------------------- o ---------------------
>>>    In God I trust - others pay cash!     <<<
Check www.typo3.com