views:

366

answers:

2

Possible Duplicate:
Loops and Garbage Collection

foreach (ObjectTypeA typea in ObjectTypeACollection) 
{
var objectTypeAProcessor= new objectTypeAProcessor();
objectTypeAProcessor.Process(typea);
}

I found the above similar code where a collection of objects was being processed at the BLL and the DAL processor was called.Will the above code lead to a memory leak / is it bad? Well a new instance is created each time right but does it get destroyed each time too? mmm...

+1  A: 

C#/.net is garbage collected, so yes, the created objects will be collected and destroyed - not neccessarily right away, but eventually. So it's not a leak.

Of course creating a new object in each iteration is more costly than doing it inside the loop (assuming the Process method does not have side-effects which would forbid you from using the same Processor object for all objects), so if you don't need a new processor for each iteration, you should move it outside.

sepp2k
But I could as you said move it outside and then I can save memory ?
abmv
You can if the class objectTypeAProcessor is written in a way, that using the same instance to process multiple objects works, which it might not be. That would not only save memory, but also the cost of allocating and collecting the object so many times.
sepp2k
+1  A: 

There is no way to tell whether there will be a leak, because we don't know what objectTypeAProcessor does. If, for instance, it subscribes to some event of another object and doesn't unsubsribes, or adds a reference to itself to another object, a reference will be kept on the objectTypeAProcessor, so it won't be collected.

If the internal implementation of objectTypeAProcessor allows it (which might not be the case), it would be better to instantiate it only once, outside the loop.

Thomas Levesque