Memory management significantly affects the performance of any application. When the application is run, .NET CLR (Common Language Runtime) allocates many objects in memory, and they stay there until they are not needed, until new objects are created and are allocated space, or until the GC runs (as it does occasionally) to release unused objects and make more space available for other objects. Most of the job is done by the GC itself, which runs intelligently and frees up space for the objects by removing those that are not needed. However, there are certain practices that can help any application to avoid performance issues and run smoothly.
In Chapter 14, Understanding .NET Core Internals and Measuring Performance, we already learned about how garbage collection works and how generations are maintained in .NET. In this chapter, we will focus on some recommended best practices and patterns that avoid memory leakage and make the application...