HandleThatError
HandleThatError

Reputation: 640

Does setting an object to null result in the C# garbage collector freeing the memory it took up?

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?

Upvotes: 0

Views: 2066

Answers (2)

goeldeepika3
goeldeepika3

Reputation: 91

Making files = null will make the string collection available for garbage collection but not free up the memory immediately. Garbage collector is called when the memory is running low. If within the scope of function file[] is too large, one way would be to get files only that you need.

    public FilesCollection loadCollectionFromDirectory(string directory) 
    {
        string errorMessage;
        FilesCollection collection = new FilesCollection(_collectionType);

        string[] files = Directory.GetFiles(directory,"*.dll");
        foreach (string file in files)
        {
           collection.AddNewFileToCollection(file, out errorMessage);
        }
       // files = null;
        return collection;
    }

Whether you make it null or not, as the function scope ends the local variable files will be available for garbage collection.

Upvotes: 2

test player
test player

Reputation: 331

I am not that sure, but why don't you try to use List<string> instead of string[]. That should do the trick about the memory :) Please let me know if that worked for you.

Upvotes: 1

Related Questions