Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing variables by reference

Status
Not open for further replies.

RbgoWeb

Programmer
Apr 10, 2002
91
NL
This function makes a copy of the argument passed to $str,
processes on the the copy which inside, could involve another copy.

function charEllipsis($str, $nchr)
{
if($nchr < 4) return;
if(strlen($str) > $nchr)
$str = substr($str, 0, ($nchr - 3)).'...';
return $str;
}

The return value is usually assigned to a variable and involves another copy like ...
$td = charEllipsis($msg, 32);
That makes a total of 2 or max 3x copying the value of $msg.

Now we modify the function to get strings by reference...
function charEllipsis(&$str, $nchr)//see the '&' ?
{
if($nchr < 4) return;
if(strlen($str) > $nchr)
$str = substr($str, 0, ($nchr - 3)).'...';
//the point of no return
}

and the function works directly on the original $msg value,
so doesn't need to copy it to a local variable,
so doesn't need to copy the local variable back to the caller. It only conditionally copies a modified version of $msg value over the original value inside the function, doing 0 or max 1x copy.
There's a lot of performance gained here, which is important on hi traffic sides presenting lots of data.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top