Se ha denunciado esta presentación.
Utilizamos tu perfil de LinkedIn y tus datos de actividad para personalizar los anuncios y mostrarte publicidad más relevante. Puedes cambiar tus preferencias de publicidad en cualquier momento.

DotNetFest - Let’s refresh our memory! Memory management in .NET

246 visualizaciones

Publicado el

The .NET Garbage Collector (GC) is really cool. It helps providing our applications with virtually unlimited memory, so we can focus on writing code instead of manually freeing up memory. But how does .NET manage that memory? What are hidden allocations? Are strings evil? It still matters to understand when and where memory is allocated. In this talk, we’ll go over the base concepts of .NET memory management and explore how .NET helps us and how we can help .NET – making our apps better. Expect profiling, Intermediate Language (IL), ClrMD and more!

Publicado en: Tecnología
  • Inicia sesión para ver los comentarios

  • Sé el primero en recomendar esto

DotNetFest - Let’s refresh our memory! Memory management in .NET

  1. 1. Let’s refresh our memory! Memory management in .NET Maarten Balliauw @maartenballiauw
  2. 2. .NET runtime Manages execution of programs Just-in-time compilation: Intermediate Language (IL) ->machine code Type safety Exception handling Security Thread management Memory management Garbage collection (GC)
  3. 3. Garbage Collector
  4. 4. Memory management and GC “Virtually unlimited memory for our applications” Big chunk of memory pre-allocated Runtime manages allocation in that chunk Garbage Collector (GC) reclaims unused memory, making it available again
  5. 5. .NET memory management 101 Memory allocation Objects allocated in “managed heap” (big chunk of memory) Allocating memory is fast, it’s just adding a pointer Some unmanaged memory is also consumed (not GC-ed) .NET CLR, Dynamic libraries, Graphics buffer, … Memory release or “Garbage Collection” (GC) Generations Large Object Heap
  6. 6. .NET memory management 101 Memory allocation Memory release or “Garbage Collection” (GC) GC releases objects no longer in use by examining application roots GC builds a graph of all the objects that are reachable from these roots Object unreachable? Remove object, release memory, compact heap Takes time to scan all objects! Generations Large Object Heap
  7. 7. .NET memory management 101 Memory allocation Memory release or “Garbage Collection” (GC) Generations Large Object Heap Generation 0 Generation 1 Generation 2 Short-lived objects (e.g. Local variables) In-between objects Long-lived objects (e.g. App’s main form)
  8. 8. .NET memory management 101 Memory allocation Memory release or “Garbage Collection” (GC) Generations Large Object Heap (LOH) Special segment for large objects (>85KB) Collected only during full garbage collection Not compacted (by default) -> fragmentation! Fragmentation can cause OutOfMemoryException
  9. 9. The .NET garbage collector Runs very often for gen0 Short-lived objects, few references, fast to clean Local variable Web request/response Higher generation Usually more references, slower to clean GC pauses the running application to do its thing Usually short, except when not… Background GC (enabled by default) Concurrent with application threads May still introduce short locks/pauses, usually just for one thread
  10. 10. The .NET garbage collector When does it run? Vague… But usually: Out of memory condition – when the system fails to allocate or re-allocate memory After some significant allocation – if X memory is allocated since previous GC Failure of allocating some native resources – internal to .NET Profiler – when triggered from profiler API Forced – when calling methods on System.GC Application moves to background GC is not guaranteed to run
  11. 11. Helping the GC, avoid pauses Optimize allocations (use struct when it makes sense, Span<T>, object pooling) Don’t allocate at all Make use of IDisposable / using statement Clean up references, giving the GC an easy job Weak references Allow the GC to collect these objects, no need for checks Finalizers Beware! Moved to finalizer queue -> always gen++
  12. 12. Helping the GC DEMO
  13. 13. Allocations
  14. 14. When is memory allocated? Not for value types (int, bool, struct, decimal, enum, float, byte, long, …) Allocated on stack, not on heap Not managed by garbage collector For reference types When you new When you load data into a variable, object, property, ...
  15. 15. Hidden allocations! Boxing! Put an int in a box Take an int out of a box Lambda’s/closures Allocate compiler-generated DisplayClass to capture state Params arrays And more! int i = 42; // boxing - wraps the value type in an "object box" // (allocating a System.Object) object o = i; // unboxing - unpacking the "object box" into an int again // (CPU effort to unwrap) int j = (int)o;
  16. 16. How to find them? Past experience Intermediate Language (IL) Profiler “Heap allocations viewer” ReSharper Heap Allocations Viewer plugin Roslyn’s Heap Allocation Analyzer Don’t do premature optimization – measure!
  17. 17. Hidden allocations DEMO ReSharper Heap Allocations Viewer plugin Roslyn’s Heap Allocation Analyzer
  18. 18. Don’t optimize what should not be optimized.
  19. 19. Measure! We know when allocations are done... ...but perhaps these don’t matter. Measure! How frequently are we allocating? How frequently are we collecting? What generation do we end up on? Are our allocations introducing pauses? (and
  20. 20. Always Be Measuring DEMO
  21. 21. Object pools / object re-use If it make sense, re-use objects Fewer allocations, fewer objects for the GC to scan Fewer memory traffic that can trigger a full GC Object pooling - object pool pattern Create a pool of objects that can be cleaned and re-used “Optimize ASP.NET Core” -
  22. 22. Garbage Collector & Allocations GC is optimized for high memory traffic in short-lived objects Use that knowledge! Don’t fear allocations! Don’t optimize what should not be optimized… GC is the concept that makes .NET / C# tick – use it! Know when allocations happen GC is awesome Gen2 collection that stop the world not so much… Measure!
  23. 23. Strings
  24. 24. Strings are objects .NET tries to make them look like a value type, but they are a reference type Read-only collection of char Length property A bunch of operator overloading Allocated on the managed heap var a = new string('-', 25); var b = a.Substring(5); var c = httpClient.GetStringAsync("");
  25. 25. String literals Are all strings on the heap? Are all strings duplicated? var a = "Hello, World!"; var b = "Hello, World!"; Console.WriteLine(a == b); Console.WriteLine(Object.ReferenceEquals(a, b)); Prints true twice. So “Hello World” only in memory once?
  26. 26. Portable Executable (PE) #UserStrings DEMO
  27. 27. String literals in #US Compile-time optimization Store literals only once in PE header metadata stream ECMA-335 standard, section II.24.2.4 Reference literals (IL: ldstr) var a = Console.ReadLine(); var b = Console.ReadLine(); Console.WriteLine(a == b); Console.WriteLine(Object.ReferenceEquals(a, b));
  28. 28. String duplicates Any .NET application has them (System.Globalization duplicates quite a few) Are they bad? .NET GC is fast for short-lived objects, so meh. Don’t waste memory with string duplicates on gen2 (but: it’s okay to have strings there)
  29. 29. String interning Store (and read) strings from the intern pool Simply call String.Intern when “allocating” or reading the string Scans intern pool and returns reference var url = ""; var stringList = new List<string>(); for (int i = 0; i < 1000000; i++) { stringList.Add(string.Intern(url + "/")); }
  30. 30. String interning caveats Why are not all strings interned by default? CPU vs. memory Not on the heap but on intern pool No GC on intern pool – all strings in memory for AppDomain lifetime! Rule of thumb Lot of long-lived, few unique -> interning good Lot of long-lived, many unique -> no benefit, memory growth Lot of short-lived -> trust the GC Measure!
  31. 31. Exploring the heap for fun and profit
  32. 32. How would you do it... Build a managed type system, store in memory, CPU/memory friendly Probably: Store type info (what’s in there, what’s the offset of fieldN, …) Store field data (just data) Store method pointers (“who you gonna call?”) Inheritance information
  33. 33. Stuff on the Stack
  34. 34. Stuff on the Managed Heap (scroll down for more...)
  35. 35. .NET memory is like a database Pointer to an “instance” Instance Pointer to Runtime Type Information (RTTI) Field values (which can be pointers in turn) RunTime Type Information Interface addresses Instance method addresses Static method addresses …
  36. 36. Theory is nice... Microsoft.Diagnostics.Runtime (ClrMD) “ClrMD is a set of advanced APIs for programmatically inspecting a crash dump of a .NET program much in the same way that the SOS Debugging Extensions (SOS) do. This allows you to write automated crash analysis for your applications as well as automate many common debugger tasks. In addition to reading crash dumps ClrMD also allows supports attaching to live processes.” “LINQ-to-heap” Maarten’s definition
  37. 37. ClrMD DEMO
  38. 38. But... Why? Programmatic insight into memory space of a running project Unit test critical paths and assert behavior (did we clean up what we expected?) Capture memory issues in running applications Other options in this space dotMemory Unit (JetBrains) Benchmark.NET
  39. 39. Conclusion
  40. 40. Conclusion Garbage Collector (GC) optimized for high memory traffic + short-lived objects Don’t fear allocations! But beware of gen2 “stop the world” String interning when lot of long-lived, few unique Don’t optimize what should not be optimized… Measure! Using a profiler/memory analysis tool ClrMD to automate inspections dotMemory Unit, Benchmark.NET, … to profile unit tests Blog series:
  41. 41. .NET Internals: stack memory management Nikolay Balakin 16:05 – Track 2
  42. 42. Thank you! @maartenballiauw