Reputation: 29
I have an ASP.NET application that has multiple helper classes. I'm a little worried about Memory leaks. Each time i want to use a helper class member function i call them like this new SampleHandler().DoFunction();
Since it dosen't have any strong reference to the object created can I guarantee whether GC will clear the memory for the object created ?
Since there is a high chance for me that I won't be using the object again in the page I started coding like this.
Note: There are numerous calls to various member functions belonging to different helper classes in the code behind file performed in the same way.
Upvotes: 1
Views: 289
Reputation: 460288
The garbage collector will take care of unused references. So you don't need to worry about a memory leak. But if you create "garbage"-objects very fast you could have temporary memory pressure.
But if you don't need the instance anyway or the instances are exchangeable you should consider to make the method static
.
public class SampleHandler
{
public static void DoFunction()
{
// ...
}
}
Then you would call it:
SampleHandler.DoFunction();
There is no problem with static methods in ASP.NET even if it's a multithreaded environment. But you should be careful with static fields.
Upvotes: 4
Reputation: 263147
Yes, since there are no other outstanding references, the instance created by new SampleHandler()
will be eligible for collection as soon as DoFunction()
returns.
There is, however, no guarantee about the time when the GC will collect that instance, as usual.
Upvotes: 8