Tips for Efficient Memory and Resource Management
I've listed a few tips in this section that can help you avoid problems. I don't have room to explain each tip in-depth here; instead, I've provided a basic description and added links where appropriate so you can explore further on your own.
Try never to refer to a short-lived object from a long lived one
to avoid promoting short-lived objects to higher generations. Note that the .NET Garbage Collector (GC) works more frequently against lower generations than against higher ones. An in-depth discussion of the .NET GC is beyond the scope of this article, but this two-part MSDN article on garbage collection (Part 1
, Part 2
) provides more background
Avoid any code that can promote an object to a higher generation unnecessarily
as shown in the code snippet below:
Use Dispose and Finalize appropriately to handle unmanaged resources
void Create (int empCode, int deptCode, double basic)
EmployeeRegister empRegister = new EmployeeRegister();
empRegister.Create(empCode, deptCode, basic);
this.empRegister = empRegister;
(for more information, see my article When and How to Use Dispose and Finalize in C#
. In fact, you should avoid implementing the Finalize
method as much as possible.
Set any objects no longer required to null prior to making any long-running calls
. Developers often set locals to null
after they're done using them, but in .NET, that's not required, as the GC can safely determine when objects are no longer needed or are not reachable, thus making them eligible for garbage collection. However, if you use machine resources such as files, database connections, or unmanaged objects, remember to release them in a finally
blocknever in a catch
Acquire resources and locks late and dispose of them as soon as possible
|Author's Note: In C#, it's best to wrap resource-handling code within a using block to ensure that the resources are disposed of properly when they're no longer needed. When you use the using statement, the .NET framework implicitly creates finally blocks for those objects that implement IDisposable.
. Ensure that you free or dispose unneeded resources and locks properly. In fact, I recommend that you avoid locking and synchronization altogether unless it's absolutely necessary. Do not lock on the this
objectit's better to lock on a private object. If you lock on the current object instance (this
), all the members of the object are also locked irrespective of whether a lock is required on them. Do not lock on object types, only on objects themselves.
Efficient Exception Management
Exceptions are errors that occur at run time. Exceptions are generally well understood but quite often used improperly. An understanding of proper exception handling is one of the more important aspects of efficient programming.
Handle only those exceptions that you know how to handle
and avoid handling those that you don't know how to handle. As Eric Gunnerson, a former member of Microsoft's C# team, says in his blog
, "the essence of exception handling is to be able to respond to a specific exception in a specific situation."
When possible, reduce the number of try...catch blocks in your code
; exceptions take longer to be processed and can reduce application performance drastically. Do not use exceptions to control an application's logic flow. Use proper validation techniques instead of exceptions to avoid throwing unnecessary exceptions.
Efficient Data Access Strategies
Prefer DataReaders to DataSets
. DataReaders are much faster than DataSets for simple sequential data access. Use a DataReader for fast data-rendering, but not to pass data between layers of the applications or through different application domainsunlike DataSets which can work in disconnected mode and can be cached, DataReaders always require an open connection. When you do have to use a DataSet, you can often set its EnableConstraints
property to false and use the BeginLoadData
methods for faster data rendering. If you are using transactions keep them short to minimize the lock durations and to improve data concurrency.
Open database connections as late as possible and close them immediately when done
. Effective use of connection pooling can increase application performance by reducing the number of roundtrips to the server. Note that each database request in a distributed environment creates network traffic that can cause performance bottlenecks and degrade the application's performance. Try to minimize the number of database connections in the application. Never hold a connection open, because that decreases the number of available connections in the connection pool and hence degrades performance if the demand for connections exceeds the pool count. See this article
for more information on connection pooling.