Reading the Google Developers PHP performance tips I saw that it isn\'t recommended to make an extra copy of a varible.
Instead of this:
$description
If you don't need a "copy" of $description, the clearer approach is definitely:
echo strip_tags($_POST['description']);
Regarding performance, as you said it, PHP will still create a resulting value in memory and assign it to a Z_Data structure thus still consuming memory. So it's not faster or less memory intensive to use the first or the second methods.
Finaly, security has nothing to do with memory consumption but you need to remember how to clean your output correctly. Using strip-tags is fine, adding slashes is another good way to prevent hackers from using XSS injection.
Also note, regarding your Copy-on-write, if you do this:
$description = 'Hello-world';
$trimmed_description = str_replace('-', ' ', $description);
$escaped = htmlentities($trimmed_description);
echo $escaped;
instead of
echo htmlentities(str_replace('-', ' ', 'Hello-world'));
The later will obviously save you memory... very little in this case, but you will still save some...
PHP's "lazy copy" only applies to arrays. The array's data is only duplicated if one copy of the array is changed, which is why it's okay for the foreach
loop to work on a copy of the original array, for instance.
Objects are passed by reference, even when not told to do so with &
. Example:
$a = new StdClass();
$b = $a;
$b->derp = "foo";
var_dump($a->derp); // "foo"
Resources are references to a resource to be used by a particular extension, so they can't meaningfully be copied.
Everything else is copied directly.
Unnecessary variables should be avoided anyway. For instance, instead of:
$step1 = 123;
$step2 = $step1 * 4;
$step3 = $step2 + 99;
$step4 = $step3 / 3;
echo $step4;
You could just write:
echo (123*4+99)/3;
(or, in this case, just echo 197;
)
The point is, unnexessary variables do create clutter and could potentially conflict with a variable you defined elsewhere.