4

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;
3
  • You could run your own tests with memory_get_usage.
    – rdiz
    Jan 25, 2016 at 8:33
  • Both result in a new string being created. It's hard to imagine there would be an measurable savings in that case. Jan 25, 2016 at 8:35
  • I know I can do that, but i'd like an answer from people who are more known with the internal workings of php what would actually be better. I can test myself just fine, but this is also for google since no resutls came up and I've wondered this more often. If I don't get a nice answer i'll do some digging myself. I'm just curious Jan 25, 2016 at 8:36

1 Answer 1

7

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;
}
3
  • Does the copy on write also happen when using reference? Jan 25, 2016 at 8:38
  • 1
    @MichaelDibbets No, then you are manipulating the original variable.
    – jeroen
    Jan 25, 2016 at 8:38
  • 1
    Could you expand your answer to include some code samples where code does get copied and where it doesn't? So future readers can easely identify their own code with said use cases incase they don't understand the copy on write. Jan 25, 2016 at 8:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.