garbage collection .net
DESCRIPTION
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.TRANSCRIPT
Ready
Ready
Wekoslav Stefanovski
Senior Developer / Seavus
Комунална Хигиена.net
Ready
Please Muteyour mobile devices
Ready
General Sponsors
Platinum Sponsors
Silver Sponsors
Gold Sponsors
Bronze Sponsors
Promoters
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
Ready
Memory Organization
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
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
Ready
Stack & Managed Heap
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.
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
Ready
Details of a garbage run
• Three phases:
– Mark
– Sweep
– Compact
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
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)
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++
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
ReadyReady
Demo:
Collecting Garbage
Ready
Finalizers and disposables
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
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
ReadyReady
Demo:
Implementing Disposable
Ready
Weak References
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)
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
ReadyReady
Demo:
Weak references
Ready
Some bad advices
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
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
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
Ready
Bottom line
• Forget this presentation (unless you need to remember it)
ReadyReady
Complete the evaluation and earn the chance to win valuable prizes from our sponsors
Questions
ReadyReady
Thank you