4

Possible Duplicate:
Garbage collector and circular reference

Is there any impact on GC performance if objects have a circular reference but are otherwise unattached to any root, and thus ripe for GC?

Would there be any benefit in having a weak ref in one direction?

Community
  • 1
  • 1
DanH
  • 3,772
  • 2
  • 27
  • 31
  • Thanks for all responses, you all answered question so difficult to pick 'correct' answer, so I gave it to the guy with least points here :) – DanH May 24 '12 at 18:45

3 Answers3

4

Is there any impact on GC performance if objects have a circular reference

No. The sweep process stops when it encounters an instance already visited. There is no diff with non-circular structures.

but are otherwise unattached to any root, and thus ripe for GC?

In that case they will not be visited at all, making it totally irrelevant how many cross links there are.

H H
  • 263,252
  • 30
  • 330
  • 514
3

Is there any impact on GC performance if objects have a circular reference but are otherwise unattached to any root, and thus ripe for GC?

Nope. Basically both objects will be eligible for garbage collection when there are no strong references... you don't need to worry about it.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

If the objects can't be reached from the root, they will not be traversed, so a circular reference won't be an issue.

Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
  • Neat! But (edge case), if the object's only reference is a weak reference, could it not have been marked at the time the last strong reference was removed, eliminating the need for a sweep altogether? I guess if a sweep is done anyway for other objects this wouldn't matter though... – Cameron May 24 '12 at 16:55
  • I'm not sure what you mean. If you mean marking an object before the GC runs, well, that would involve searching the entire root for remaining references, which the GC does anyway, so it would be quite inefficient. – Kendall Frey May 24 '12 at 17:00
  • Oh. I was under the impression there was reference counting in addition to mark-and-sweep. Never mind! – Cameron May 24 '12 at 17:53