Home > Back-end >  Freeing memory while iterating through list before reaching end of loop
Freeing memory while iterating through list before reaching end of loop

Time:11-19

I'm working with various lists and types under memory constraints and would like to free up memory while iterating through a list, so I've set up a generic example:

public class Test
{
    List<PersonClass> personList = new(450000);

    public Test()
    {
        for(int i = 0; i < 450000; i  )
        {
            personList.Add(new PersonClass());
        }
    }

    public List<InfoClass> GetUpdatedList(List<PersonClass> personList)
    {
        List<InfoClass> secondList = new();
        
        for(int i=personList.Count - 1; i > -1; i--)
        {
            var aPerson = personList[i];
            
            secondList.Add(new InfoClass()
            {
                FirstName = aPerson.FirstName,
                LastName = aPerson.LastName
            });
            
            personList.RemoveAt(i);
        }

        return secondList;
    }
    
    public class PersonClass
    {
        public string FirstName { get; set; } = "Something Random";
        public string LastName { get; set; } = "Something Else Random";
    }

    public class InfoClass
    {
        public string FirstName { get; set; } = "Something Random";
        public string LastName { get; set; } = "Something Else Random";
        public string StateName { get; set; } = "Something Random";
        public string CityName { get; set; } = "Something Else Random";
    }
}

How can I free up memory while removing elements before reaching the end of the loop?

CodePudding user response:

You can save a lot of memory if InfoClass contains a reference to the appropriate PersonClass, instead of creating new strings.

If InfoClass is a summary of many other objects, try just storing references to the other objects, instead of duplicating the properties

CodePudding user response:

A couple of things:

  1. Variables will be freed automatically when they go out of scope. If you declare a variable within curly braces, that is its scope.

  2. The garbage collector will automatically run when there is sufficient memory pressure to trigger it. Memory pressure can be caused by a number of things, but one of them is the inability to allocate enough contiguous free space on the heap for a new object.

  3. Manually running GC.Collect() is frowned upon for a number of reasons, not the least of which is that it's slow. You certainly don't want to be doing it in a loop of any kind.

  4. If you don't KNOW how much memory is being used by your application, and if that memory is higher than the amount of memory available to you at runtime, what you're proposing is premature optimization, the root of all evil. There are tools (some of them built right into Visual Studio) that will let you determine how much memory your application is using when it runs. Once you have that information, then you can make an informed decision about whether or not you should even worry about this sort of an optimization.

  5. If you must optimize, you may want to consider using a struct instead of a class if you know that the class can be converted to one. structs are allocated on the stack instead of the heap, saving a little bit of memory, but they must be read-only and must meet specific size requirements. But they will be deallocated immmediately when they go out of scope, and heap memory won't be an issue.

  • Related