Memory Leaks in .NET applications and Some Tips To avoid them

Developers using .NET often make memory leak tracking a low
priority because the common language runtime takes care of garbage collection.
What few developers realize, however, is that their objects’ lifespans, along with their size and what other objects have
been instantiated, all affect how they are cleaned up. Depending on the
particular circumstances, these combinations can negatively affect performance,
especially over the lifetime of an application.

The tips for reducing the Memory

1) As we all have heard many times from the experts –
Strings are very expensive in .Net and we have not done well in using them

a. Use the .ToString() method intelligently which creates a new instance of the

b. Be aware of string comparisons,
especially when doing string insensitive comparisons. For example, do not do
“if ( string1.ToUpper() == string2.ToUpper() )” – this
creates 2 new strings. Instead – use the string.Compare


effective use of variables to prevent the re-creation of strings.

For example –

I have seen some code written by inexperienced programmers
such as:

If (! hashTable.Contains ( SomeGuidID.ToString() )

hashTable.Add (SomeGuidID.ToString(), 1)

What this line
effectively did was create 2 strings, when a string variable could have been
declared and the ToString() method called only once.

other case that I’ve seen is the use of concatenated strings to form a key for
a hash table. For example:

hashTable.Add( ID1.ToString() + ID2.ToString(), 1 )

This is again inefficient as strings are bigger (in Bytes)
than a string. A Guid is 24 bytes where as a Guid.ToString() string is
40. That is a 67% increase in size over what is needed If
you need a concatenated key for use in a hash table, you can create a small and
efficient in-line class to handle that.

2) Recursive functions – due to the way that the heap is
managed, apparently recursive functions are very expensive as well and should
be avoided. Always try to avoid recursive functions wherever possible and just
use loops.

3) Maintaining the data tables has proved a quite heavy on
memory (I guess when you think about it, it
effectively doubles the memory usage of the raw data). Use DataTables
in the sistuation only if the data changes very

More tips to come later……………………………


With Regards,

UVN PardhaSaradhi


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s