45
Effective Memory Management - Memory Hygiene

Effective Memory Management - Memory Hygiene

Embed Size (px)

Citation preview

PowerPoint Presentation

Effective Memory Management - Memory Hygiene

1

2

Perfectionism?

3

4

5

6

7

Performance GoalsNameTarget (ms)Upper Bound (ms)UX / FeedbackInstant50010000Long, show Progress Dialog w/CancelExtended>500>10000Long enough for the user to switch to something else

8

premature optimization is the root of all evil- Donald E. Knuth, Structured Programming with go to Statements

9

-Performance is a feature?-No!

10

Any memory issues?

usingSystem; namespaceConsoleApplication1 { internalclassProgram { privatestaticvoidMain(string[]args) { Console.WriteLine("ThisOShas{0}objectgenerations.",(GC.MaxGeneration+1)); varmyClass=newMyClass("First",100); Console.WriteLine("\nGenerationofmyClassis:{0}",GC.GetGeneration(myClass)); varamount=50000000; vartonsOfObjects=newobject[amount]; for(vari=0;i= 85,000 bytes) gen3

usingSystem; usingSystem.IO; namespaceConsoleApplication1 { classProgram { staticvoidMain(string[]args) { varcandidateToLargeObjectHeap=newlong[85000/8]; varmaxGen=GC.MaxGeneration; varobjectGen=GC.GetGeneration(candidateToLargeObjectHeap); Console.WriteLine($"ObjectSize:{GetObjectSize(candidateToLargeObjectHeap)}"); Console.WriteLine($"{nameof(maxGen)}:{maxGen}"); Console.WriteLine($"{nameof(objectGen)}:{objectGen}"); } privatestaticintGetObjectSize(objecttestObject) { varbf=newSystem.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); using(varms=newMemoryStream()) { bf.Serialize(ms,testObject); returnms.ToArray().Length; } } } } 13

Collector

Stop the world!

14

What happens during a collection

15

Stop collecting during critical code pathsWithin .NET 4.6GC.TryStartNoGCRegionGC.EndNoGCRegion

Before .NET 4.6GCSettings.LatencyMode = LowLatency

16

Garbage Collection NotificationsGC.WaitForFullGCApproachif (GC.WaitForFullGCApproach() == GCNotificationStatus.Succeeded) // Method that tells the queuing server to not direct requests to this server.

GC.WaitForFullGCCompleteif (GC.WaitForFullGCComplete() == GCNotificationStatus.Succeeded)// Informs the queuing system that this server is ready to accept requests again.

17

Workstation GC with concurrent GC on

18

Server GC with concurrent GC off

19

Server GC with concurrent GC on

20

Configure different GC modes Element

Element

21

Efficiency is not where collect, but where do not allocateAllocation is the root of all evil

22

Strings

23

Strings | String.FormatcommonOptimal

int i = 5;String.Format("i = {0}", i);24

Strings | String Interpolation (C#6.0)commonOptimal

int i = 5;var formatted = $"i = {i}";25

Closure

26

Closure | SimpleSource

Compiler-generated code

usingSystem; namespaceConsoleApplication1 { classProgram { staticvoidMain(string[]args) { intcount=0; Actionaction=()=> { count++; }; action(); } } }27

Closure | ComplexSourceCompiler-generated code

usingSystem; usingFluentTasks; namespaceConsoleApplication1 { classProgram { staticvoidMain(string[]args) { vartasks=newFluentTask(); varstring1="toBeCaptured1"; varstring2="toBeCaptured2"; tasks.AddTask(()=> { vartemp=string1+"somecoolinformation"; }, ()=>{vartemp=string2+"somegreatinformation";}); } } } namespaceFluentTasks { publicclassFluentTask { Action_taskAction; Action_onComplete; publicFluentTaskAddTask(ActiontaskAction,ActiononComplete) { _taskAction=taskAction; _onComplete=onComplete; returnthis; } } }28

IList vs List

29

IList vs ListIlist (referencesource)List (referencesource)

30

Create empty collectionCommon referencesource Optimal referencesource

31

Resizing CollectionsDictionary.ResizeList.SetCapacity

usingSystem; usingSystem.Collections.Generic; namespaceConsoleApplication1 { internalclassProgram { privatestaticvoidMain(string[]args) { constintn=1000000; varcapacities=newHashSet(); varlist=newList(); for(vari=0;i= 85,000 bytes) LOH does not employ compactionLOH size only growsResult in memory fragmentation leads to OutOfMemory

33

Microsoft.IO.RecycableMemoryStream

34

- Stop! Youre crazy!!!

- Really?

35

Welcome to crazy world!

36

FrugalStructListreferencesource

referencesource

37

ObjectPoolreferencesourcereferencesource

38

Boxesreferencesourcereferencesource

39

SmallConcurrentSetOfInts

40

UnionCollection

41

OneOrMany

42

Essentials toolsClr Heap Allocation Analyzer - https://visualstudiogallery.msdn.microsoft.com/f9b47b93-8675-4ae0-9c52-5da8027c4bb8 Heap Allocation Viewer (ReSharper) - https://resharper-plugins.jetbrains.com/packages/ReSharper.HeapView Analyze Performance While Debugging in Visual Studio 2015 - https://msdn.microsoft.com/en-us/magazine/dn973013.aspx LINQPad- https://www.linqpad.net/dotPeek - https://www.jetbrains.com/decompiler/dotMemory - https://www.jetbrains.com/dotmemory/dotMemory Unit - https://www.jetbrains.com/dotmemory/unit/ Process Monitor - https://technet.microsoft.com/en-us/library/bb896645.aspx SourceBrowser - https://github.com/KirillOsenkov/SourceBrowser

43

Further readingGarbage Collection Design - https://github.com/dotnet/coreclr/blob/master/Documentation/botr/garbage-collection.md Mpgo - https://msdn.microsoft.com/en-us/library/hh873180(v=vs.110).aspxFundamentals of Garbage Collection - https://msdn.microsoft.com/en-us/library/ee787088(v=vs.110).aspx GC Performance Counters - http://blogs.msdn.com/b/maoni/archive/2004/06/03/148029.aspx Garbage Collector Basics and Performance Hints - https://msdn.microsoft.com/en-us/library/ms973837.aspx A new stackalloc operator for reference types with CoreCLR and Roslyn - https://github.com/xoofx/StackAllocForClassThe Garbage Collection Handbook - http://www.amazon.com/Garbage-Collection-Handbook-Management-Algorithms/dp/1420082795 .NET Type Internals - http://www.codeproject.com/Articles/20481/NET-Type-Internals-From-a-Microsoft-CLR-Perspecti Background and Foreground GC - http://blogs.msdn.com/b/salvapatuel/archive/2009/06/10/background-and-foreground-gc-in-net-4.aspx The 5 stages of solving real-life .NET memory problems - http://www.red-gate.com/products/dotnet-development/ants-memory-profiler/solving-memory-problems/index Under the Hood of .NET Memory Management - https://www.simple-talk.com/redgatebooks/ChrisFarrell/Under_the_Hood_of_NET_Management.pdf

44

Questions?

https://twitter.com/Ky7m http://ifesenko.comhttp://ifesenko.com/go/NMH

45