I have a method that gets called many times, repeatedly.
public FilesCollection loadCollectionFromDirectory(string directory)
{
string errorMessage;
FilesCollection collection = new FilesCollection(_collectionType);
string[] files = Directory.GetFiles(directory);
foreach (string file in files)
{
if(file.EndsWith(".dll"))
collection.AddNewFileToCollection(file, out errorMessage);
}
files = null;
return collection;
}
I'm pretty sure the method calling this method is sucking up a ton of memory because of the string array that gets initialized every single time this method runs. From what I understand, each time this method is run again, the string array is set to a new collection of strings and the old strings remain in memory until garbage collection gets to them. Is that correct? Garbage collection isn't getting to them fast enough, as far as I can tell. There are numerous other problems affecting the Out Of Memory exception I'm getting but I think too many "ghost strings" is one of the big causes. If I set files = null like I'm doing right now, will that result in GC occurring earlier? Have I misunderstood the fundamentals of garbage collection and memory management?
I suppose my biggest question is - if I do string[] files = Directory.GetFiles(directory) over and over without doing something about the array, will this result in a bunch of ghost strings clogging up my system?