php-src icon indicating copy to clipboard operation
php-src copied to clipboard

Self-reference is counted as circular reference

Open Jumping-Beaver opened this issue 4 years ago • 3 comments

Description

A self-reference is regarded as a circular reference with implications on garbage collection. A real-world usecase where this can be relevant is setting an instance variable to an anonymous function, which is also a kind of self-reference. Such objects need to be garbage-collected by gc_collect_cycles when creating many of them, or memory exhaustion can result. Would it be possible to make the reference counting smarter to avoid this?

<?php

$sr = new SelfRef;
unset($sr);
print("End of script\n");

class SelfRef
{
	function __construct()
	{
		$this->self_ref = $this;
		#$this->self_ref = function() { };
	}
	function __destruct()
	{
		print("__destruct\n");
	}
}

Resulted in this output:

End of script
__destruct

But I expected this output instead:

__destruct
End of script

PHP Version

PHP 8.0.14

Operating System

No response

Jumping-Beaver avatar Jan 02 '22 14:01 Jumping-Beaver

Well, certainly not a bug, but rather a feature request. However, making the reference counting smarter, would also make it more complex, and that complexity might defeat (part of) its purpose.

cmb69 avatar Jan 02 '22 17:01 cmb69

On further consideration, I don't think attempting to cater to self references wrt. reference counting in the engine makes sense; applications which don't need that would have to pay the price. Instead, try to avoid circular references, and when you need them, consider to (track their use and) call gc_collect_cycles() at appropriate times.

cmb69 avatar Jan 02 '22 18:01 cmb69

Yeah, I don't think it makes sense to try and special case these kinds of "trivial" cycles. It's still a cycle and should be handled by cyclic GC. Something we need to improve though is GC scheduling, to avoid hitting the memory limit if running GC would prevent that.

nikic avatar Jan 02 '22 21:01 nikic