Please save me from myself (or reassure me that I’m not being completely misguided)
I’ve gotten into the habit of writing code something like the following:
function foo($aUserObject) {
$theUserUID = $aUserObject->uid;
$aDeepValue = $aUserObject->property[123][456];
[more code, in which much use is made of $theUserUID and $aDeepValue]
}
My strategy is probably obvious: I’m taking the attitude that it’s going to be easier for the PHP interpreter to handle a variable reference than to continually dig into the object to find the thing I’m interested in, so I should be getting some performance benefit. In addition, my code is perhaps a bit more bug-free and understandable (as long as I remember the meanings of the variable names), since I’m mostly writing simple variable names instead of longer and more complex object/array references where my fingers are more likely to slip. I understand that there’s a price for doing this — there are now two copies of $aUserObject->uid and $aUserObject->property[123][456] floating around, and if those values are large, the additional memory costs could add up. But I’m currently willing to pay that price in exchange for the (alleged) benefits.
Or, that’s what I’m telling myself anyway, based on my naive theory of how PHP underpinnings work. But reality, especially when opcode caching tools like APC get introduced, may be a totally different matter. Any more informed opinions out there, that might push me one way or another?
Thanks!
I can reassure you, you’re wrong when you say:
Unless
$theUserUIDis modified or referenced, it points to the exact same memory location that the property you fetched it from.You can even do:
And it won’t take any more memory than:
A copy will be created in the following scenarios:
It’s called copy-on-write.
Tip: Try debug_zval_dump and memory_get_usage and notice the
refcountthat increases, while the memory usage stays the same.