Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it better t use &$ with large strings to save memory?

So I was wondering, in effort to save some precious memory allocation on a pretty busy server.

if I have roughly 1-5mb strings getting tossed around my program whilst it compiles the final output, is it better to explictly pass them around by reference? Would that save memory or not?

So basically the question is: Memory wise what's better, A or B And is it worth the effort?

A:

function something($whoa) {
  $whoa .= 'bar';
  return $whoa;
}
$baz = 'foo';
$baz = something($baz);
echo $baz;

B:

function something(&$whoa) {
  $whoa .= 'bar';
}
$baz = 'foo';
something($baz);
echo $baz;
like image 917
Tschallacka Avatar asked Mar 14 '23 12:03

Tschallacka


1 Answers

Yes.

PHP uses copy-on-write so it will not copy your strings if you just use them (for example display them). But as soon as you start to manipulate them like you do in your function, a copy will be made and the amount of memory used will increase.

As mentioned in the comments, you can easily measure that using memory_get_usage().

Examples:

A copy will be made (the value is manipulated so a new one will be written):

function something($whoa) {
  $whoa .= 'bar';
  return $whoa;
}

No copy will be made:

function somethingElse($whoa) {
  echo $whoa;
  return true;
}
like image 128
jeroen Avatar answered Mar 29 '23 18:03

jeroen