Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Garbage Collection .Net


Published on

This session is a look under the hood of the memory management done by the .net framework. It strives to explain the complexities that the garbage collector manages for us, and the means through which it does its magic.

Through hands-on examples, It shows places where we can help or hinder the performance of our application, if we understand the effects of the code we write on the underlying framework.

Published in: Software
  • Be the first to comment

Garbage Collection .Net

  1. 1. Ready
  2. 2. Ready Wekoslav Stefanovski Senior Developer / Seavus Комунална Хигиена.net
  3. 3. Ready Please Mute your mobile devices
  4. 4. Ready General Sponsors Platinum Sponsors Silver Sponsors Gold Sponsors Bronze Sponsors Promoters
  5. 5. Ready Agenda • How is memory organized in .net , how is it managed and by whom? • What are garbage generations? • What are finalizers, and why should I care? • What are weak references (and why should I care)? • Things that you should never do
  6. 6. Ready Memory Organization
  7. 7. Ready Stack & Managed Heap • Stack – typically a per-thread 1MB structure. – (Mainly) used for value types – Local variables (and parameters) usually live here – Keeps track of execution chain – Uses stack frames – Ultra fast, very light – No garbage collection, because none is needed
  8. 8. Ready Stack & Managed Heap • Heap – Used for everything not elsewhere – Not a monolith structure, actually 4 heaps • Small object heap, generation 0 • Small object heap, generation 1 • Small object heap, generation 2 • Large object heap – Very fast – The domain of The Collector
  9. 9. Ready Stack & Managed Heap
  10. 10. Ready Garbage collector goals • To enable you to develop your application without having to free memory. • To reclaim objects that are no longer being used, clears their memory, and keeps the memory available for future allocations. • To provide memory safety by making sure that an object cannot use the content of another object. • To allocate objects on the managed heap efficiently.
  11. 11. Ready Garbage collector information • Runs on top of the Windows (or other) memory management. • Does so in 3 generations (Gen0, Gen1, Gen2) • Works on a separate thread(s) • Can run concurrently (in the background) or separately • Optimized for latency or throughput • Essentially a non-real-time component of .net
  12. 12. Ready Details of a garbage run • Three phases: – Mark – Sweep – Compact
  13. 13. Ready Details of a garbage run - mark • The assumption is: Everything is dead until proven alive • The Collector makes a list of root objects (from globals, things on the stack and processor registers) • Marks referenced objects as alive • Mark everything referenced by referenced object as alive
  14. 14. Ready Details of a garbage run - sweep • Move everything that is marked alive to the next generation • Fix the references, so they are working • Nuke the current generation (from orbit)
  15. 15. Ready Details of a garbage run - compact • On Gen0 and Gen1 runs, zeroes out everything • On Gen2 zeroes everything that is not marked as live • Moves the objects next to one another • We can easily allocate new objects – includes only reserving the required memory size • Constructing new objects is very cheap and fast in .net • It’s actually faster than C++
  16. 16. Ready Large Object Heap • Special handling for large objects • Too heavy to move – so nobody moves them • Limit is 85KB • Not collected on Gen0 or Gen1 collections • Collected on Gen2 collections • It is never compacted, so it can get heavily fragmented
  17. 17. ReadyReady Demo: Collecting Garbage
  18. 18. Ready Finalizers and disposables
  19. 19. Ready Finalizers • .net does not have destructors • They are called finalizers • Finalizers are executed non-deterministically • Special root collection, called freachable queue • Causes generational promotion • It takes at least two runs of different generations to get rid of a finalizable object • Exception thrown in finalizers are uncatchable • Don’t use them if you do not need them
  20. 20. Ready Disposing • Managed way to free acquired resources • Integrated in C# with the using keyword • It can, but should not throw exception • The object should be disposed of after use • No further use is expected after disposal is done • It can be implemented in a special pattern so that it plays nicely with finalizers
  21. 21. ReadyReady Demo: Implementing Disposable
  22. 22. Ready Weak References
  23. 23. Ready Weak references • Standard references are considered strong • Weak reference is a non-binding reference • It might be there, but then again, it mightn’t • Commonly used by reference counting memory managers (not required in .net)
  24. 24. Ready Weak references • The garbage collector will collect objects that only have weak references • Common scenario: objects that are somewhat expensive to keep, but not very complicated to get (i.e. MRU document list) • Never trust IsAlive when it returns true
  25. 25. ReadyReady Demo: Weak references
  26. 26. Ready Some bad advices
  27. 27. Ready GC.Collect • Rule 1: Don’t • Rule 2: Only call it if you can prove you know more that the GC • If you have lots of recently deceased objects in Generation 2 • Rule 1 supersedes rule 2
  28. 28. Ready Performance Measuring • Never optimize what does need optimization • It’s very very rare that a nicely written program has intense memory pressure • Always monitor performance • Use performance counters – the GC has some nice ones • Don’t always trust them • Always profile performance (speed and memory wise) • Lots of profilers available, included with Visual Studio • Measure, measure, measure
  29. 29. Ready Finalizers • Rule 1: Don’t use finalizers • Rule 2: Don’t leak resources • Rule 3: If you have to use finalizers, use the Dispose pattern
  30. 30. Ready Bottom line • Forget this presentation (unless you need to remember it)
  31. 31. ReadyReady Complete the evaluation and earn the chance to win valuable prizes from our sponsors Questions
  32. 32. ReadyReady Thank you