0

I'm trying to understand when memory gets allocated and when the garbage collector collects garbage. Let's say that I have some code like this:

foreach (FileInfo f in File){
    foreach (DataAtrribute d in f){
        string name = d.name;
    }
}

Let's say there are thousands of FileInfo objects held in an array inside of a File object. Let's say that inside each FileInfo object is a collection containing multiple DataAttribute objects. Will this code result in many blocks of memory being reserved over and over for "string name" since instead of having a single static string named name I'm doing 'string name = d.name" over and over? Or does the garbage collector work fast enough to avoid this and to keep free memory CONTIGUOUS?

Thanks.

HandleThatError
  • 598
  • 7
  • 29
  • When you create new objects inside a loop you create new objects inside a loop. They will each take up memory. Every object that has a string property called "name" will have its own property. If that property, for each of all those objects, refer to different string instances, then there will be many string instances in memory. In general the garbage collector should work fast enough to keep garbage away. – Lasse V. Karlsen Dec 08 '15 at 23:50
  • @LasseV.Karlsen If those foreach loops were inside of a class, could I reduce the number of string instances in memory by doing "string name" just once as a class variable? – HandleThatError Dec 08 '15 at 23:53
  • 1
    No, `string name` does not allocate anything, it just declares a single local variable that is given a reference to an existing string. The problem here is that you have an out of memory exception and is doing debugging by proxy, you're searching for the needle in the haystack but you're describing the haystack to us, leaving out the needle. There is no substitute for normal debugging here, except for a specialized tool for finding potential memory leaks. – Lasse V. Karlsen Dec 08 '15 at 23:55
  • I see. Do you have any recommendations for tools? Would Visual Studio 2012's profiling tools be sufficient? Can you also recommend a book on C# .NET memory management? Thanks so much for your time. – HandleThatError Dec 08 '15 at 23:56

1 Answers1

2

string name = d.name; defines a reference to a string on the stack, and assigns that references to point to an existing string object in memory, so there isn't any heap allocation.

Timothy Shields
  • 75,459
  • 18
  • 120
  • 173