What does the PHP assignment operator do?

I happen to read this http://code.google.com/speed/articles/optimizing-php.html

He claims that this code

$description = strip_tags($_POST['description']); echo $description; 

should be optimized as shown below

 echo strip_tags($_POST['description']); 

However, in my opinion, an assignment operation in PHP does not necessarily create a copy in memory.

Only one copy of "abc" is in memory.

 $a = $b = "abc"; 

It consumes more memory only when changing one variable.

 $a = $b = "abc"; $a = "xyz"; 

Is it correct?

+6
source share
3 answers

should be optimized as shown below

This is only a good idea if you do not need to store it, thereby avoiding unnecessary memory consumption. However, if you need to output the same thing again later, it is better to store it in a variable to avoid another function call.

Is it correct?

Yes. It is called copy-on-write.

+5
source

In the first example, if a variable is used only once, then it makes no sense to make the variable in the first place, just immediately respond to the results of the statements, there is no need for a variable.

In the second example, PHP has something called copy-on-write. This means that if you have two variables pointing to the same thing, they both simply point to one bit of memory. That is, until one of the variables is written, then a copy will be made, and a change will be made for this copy.

+1
source

The author has a point, because copying data into a variable will store this data in memory until the variable is unset . If you do not need data later, it really lost memory.

Otherwise, there is no difference in the consumption of peak memory between the two methods, so its argument (β€œcopying”) is incorrect.

+1
source

Source: https://habr.com/ru/post/889754/


All Articles