[Idea] Modification to Mirror struct to support dynamic reference cycle detection


(Uri Brecher) #1

I would like to suggest the following modification to the
Mirror.DisplayStyle enum:

for the Class case I would add an associated value of type ReferenceType
(better naming is welcomed) which is yet another enum:

enum ReferenceType {
    case Strong, Weak, Unowned
}

enum Mirror.DisplayStyle {
...
   case Class(ReferenceType)
...
}

This modification could assist in building better tools for detection of
strong reference cycles which cause memory leaks.
The more general mathematical concept of a reference cycle is a 'strongly
connected component' or SCC.

One possible tool could be an implementation of an algorithm to find all
SCCs in a graph of all strong references discoverable from a certain
working set (a set of immediately accessible references).
This algorithm can generate the following data:
1. count of SCC found (should be zero in order to avoid leaks)
2. size of largest SCC (size can be measured by either node count, edge
count or the sum of both)
3. gather all objects of an SCC into an Array<AnyObject>
4. gather all strong references of an SCC into an Array<(AnyObject,
String)> where a String would be a name of a stored property in the object.
Gathering this information periodically during a profiling session could
potentially assist developers in detecting the formation of SCC and maybe
even lead to finding the source of the problem.

The complexity of finding all SCC in a graph is O(m+n) time and space,
where m is object count and n is count of all strong object references.
So this tool has performance impact and is not advisable to run on a
production system.