7

In another question, Stephen C says:

A second concern is that there are runtime overheads with using weak references. The obvious costs are those of creating weak references and calling get on them. A less obvious cost is that significant extra work needs to be done each time the GC runs.

So what exactly is the cost to the GC of a weak ref? What extra work does it need to do, and how big of a deal is it? I can make some educated guesses, but am interested in the actual mechanics.

Community
  • 1
  • 1
scobi
  • 14,252
  • 13
  • 80
  • 114

1 Answers1

3

Please check Jeffrey Richter's article about Memory Management in .NET it must clear up things a little.

Incognito
  • 16,567
  • 9
  • 52
  • 74
  • 2
    +1 nice article. So basicly the overhead of weak references is only when you have a lot of weak references because the GC has to check if the weak reference'd target is going to be cleaned up, if that is the case, set the weak reference's target to null. In any case, I would find it strange if anyone has that many weak references in their application. Generally you need none. – Stormenet May 17 '10 at 13:00
  • @Stormenet Well, using [`ConditionalWeakTable(T)`](https://msdn.microsoft.com/en-us/library/dd287757(v=vs.110).aspx) to tack metadata onto arbitrary objects without having to worry about cleaning up entries in your metadata table when those arbitrary objects get garbage collected can be quite handy sometimes. Depending on what you’re doing, I’d imagine it’d be pretty easy to create *a lot* of them. – binki Jan 08 '16 at 06:14
  • archive.org link https://web.archive.org/web/20081220175048/http://msdn.microsoft.com/en-us/magazine/bb985011.aspx – Baggers Aug 03 '18 at 12:40