Reputation: 293
Is there a way in PHP to figure out from where an object is being referenced, in order to find stale references not actually needed any more?
Some background:
I am debugging/optimizing a large system written in PHP, trying to reduce the memory footprint of the system when running some large batch processing jobs.
The flow is basically:
1) Setup some context/objects needed for all processing
2) Iterate N times operating on objects only related to objects setup in #1, there is no relation/coupling between the individual objects created in the loop
Given big enough N the system will always run out of memory, even though each object created in step #2 should be able to be garbage collected after the processing is done on that specific object.
At the end of each iteration in step 2 I am doing the following:
debug_zval_dump($lObj); echo gc_collect_cycles();
I am consequently seeing the following results:
debug_zval_dump: refcount(3) gc_collect_cycles: 0
The above makes me assume that for some reason there are some stale references to the object being kept somewhere in the system, but I'm having trouble finding them just by inspecting the code.
Any help greatly appreciated!
Upvotes: 0
Views: 186
Reputation: 165201
The short answer is that what you're doing is not possible. From a variable, it's impossible to figure out what other variables are pointing to it (well, impossible from PHP at least).
What I would suggest is to setup an Object Pool. You "release" the object when you're done with it. That way, the pool knows if you can re-use that object (or throw it away if there are too many free objects).
In short, the memory management needs to be cooperative across multiple pieces of code. You can't expect them to just work transparently, if you're storing copies on either side.
As far as debug_zval_dump()
, I would be very wary of trusting it. If the variable is a reference, you need to pass by reference (which you can't anymore in 5.4+). So if the variable is a reference, it will always give you a refcount of 1. And if it's not a reference, the true refcount will be increased by 1. It's useful in some edge-case scenarios, but I wouldn't rely on it for anything...
Upvotes: 3