C # instance in foreach loop?

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 in a BLL was processed and the DAL processor was called. Will the above code lead to memory leak / is it bad? Well, a new instance is created every time, but is it also destroyed every time? mmm ...

+2


source to share


2 answers


C # /. NET is garbage collection, so yes, the objects created will be collected and destroyed - not necessarily right away, but eventually. So this is not a leak.



Of course, creating a new object on each iteration is more costly than executing inside a loop (assuming the Process method has no side effects that would prevent you from using the same Processor object for all objects), so if you don't need a new processor for each iteration, you have to move it outside.

+1


source


There is no way to tell if there will be a leak because we don't know what it does objectTypeAProcessor

. If, for example, it attaches to some event of another object and does not drop the subscription, or adds a reference to itself to another object, the reference will be stored on the TypeAProcessor object, so it will not be collected.



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

+1


source







All Articles