Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do references use more memory?

Shouldn't they make the script use less memory?

function a(&$var); uses more memory than function a($var);

and foreach($array as $k => &$v) uses more memory than foreach($array as $k => $v)

For example $var uses 24 MB. If I pass it by reference it uses 27 MB

like image 761
user1806244 Avatar asked May 15 '26 06:05

user1806244


1 Answers

(unfortunately) Without being able to explain the magic under the hood inside the zend engine in detail, I'm referring to the documentation:

References in PHP are a means to access the same variable content by different names. They are not like C pointers; for instance, you cannot perform pointer arithmetic using them, they are not actual memory addresses, and so on. See What References Are Not for more information. Instead, they are symbol table aliases. Note that in PHP, variable name and variable content are different, so the same content can have different names. The closest analogy is with Unix filenames and files - variable names are directory entries, while variable content is the file itself. References can be likened to hardlinking in Unix filesystem.

I think the comparison with a unix file system is easy to understand. If you have multiple names for a file you'll need additional memory to store those names.

like image 154
hek2mgl Avatar answered May 17 '26 20:05

hek2mgl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!