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;
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With