Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is your "Watch out" list regarding avoiding memory leaks when you write .NET code?

What do you keep on mind to avoid memory leaks when you write thousands lines of .NET code? I'm a big fan of prevention over inspection , there is a famous example regarding this point which is using a "StringBuilder" to combine strings instead of "String1+String2", so what is else out there from your coding experience?

thanks in advance for sharing your thoughts.

like image 770
Mohamed Faramawi Avatar asked Oct 30 '08 22:10

Mohamed Faramawi


4 Answers

Events. Always unsubscribe from events, this is single most leak-providing feature of .NET.

Subscribing to event means "notify and hold me while you are alive", not "notify me while I'm alive". Failing to unsubscribe from event usually leads to large clusters of hanging objects, especially in UI.

like image 146
Ilya Ryzhenkov Avatar answered Jun 03 '23 07:06

Ilya Ryzhenkov


set root references to null after use.

More info here: If we forget to null out rooted references, the GC is prevented from efficiently freeing memory as quickly as possible, resulting in a larger memory footprint for the application. The problem can be subtle, such as a method that creates a large graph of temporary objects before making a remote call like a database query or call to a Web service. If a garbage collection happens during the remote call, the entire graph is marked reachable and is not collected. This becomes even more costly because objects surviving a collection are promoted to the next generation, which can lead to a midlife crisis.

like image 43
Gulzar Nazim Avatar answered Jun 03 '23 07:06

Gulzar Nazim


Be aware of the complexity of everything you do, as far as possible, and think about each situation instead of relying on dogma. For instance, also be aware that using a StringBuilder isn't always the right way to join strings :)

Where possible, try to stream data rather than buffering it - you need to be careful here when it comes to LINQ to Objects, understanding which operators buffer and which stream (and which do both with different sequences).

(Neither of these are really memory "leaks" as such - but I'm thinking about places where you can rapidly use more memory than you expect to.)

like image 24
Jon Skeet Avatar answered Jun 03 '23 06:06

Jon Skeet


Make sure you always dispose IDisposable objects. Furthermore, try to always use "using (...)" blocks to declare disposable objects.

like image 42
Ty. Avatar answered Jun 03 '23 05:06

Ty.