Garbage collection occurs when the system is low on available physical memory or the GC.Collect() method is called explicitly in your application code. Objects that are no longer in use or are inaccessible from the root are candidates for garbage collection.

While the .NET garbage collector, or GC, is adept at reclaiming memory occupied by managed objects, there may be times when it comes under pressure, i.e., when it must devote more time to collecting such objects. When the GC is under pressure to clean up objects, your application will spend far more time garbage collecting than executing instructions.

Naurally, this GC pressure is detrimental to the application’s performance. The good news is, you can avoid GC pressure in your .NET and .NET Core applications by following certain best practices. This article talks about those best practices, using code examples where applicable.

Note that we will be taking advantage of BenchmarkDotNet to track performance of the methods. If you’re not familiar with BenchmarkDotNet, I suggest reading this article first.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.

Create a console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core console application project in Visual Studio.

Copyright © 2021 IDG Communications, Inc.