In this blog we will discuss about best practices for memory management in .Net framework. Even though the .Net framework has its own garbage collection support still as developers we have to think and write code that minimizes memory wastage. Following are some key points from memory management perspective that we should keep in mind while writing code:
1) We should create objects in the application only at the time when they are required.
2) We should carefully decide the scope for each variable and object in the application, if they are required inside methods then we should only declare them inside methods rather than making them private.
3) We should minimize the use of static variables or instances.
4) All string manipulation parts of the code should be using StringBuilder or string.Format and not '+' operator for concatenation.
5) It is a must that all Disposable objects should be disposed after they have been used. This will ensure we do not leave unmanaged resources in the application.
7) We should try to minimize boxing and unboxing in the system.
8) For reusable objects in the system we should create a cache or a pool of objects.
9) If the object/instance only composes of primitive types we should use struct instead of class.
10) We should avoid using GC.Collect() manually.
11) We should use application profilers regularly to keep track of memory usage in the application.
Using the above best practices in the application will help in creating application with efficient memory usage.
0 Comment(s)