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:
Variables will be freed automatically when they go out of scope. If you declare a variable within curly braces, that is its scope.
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.
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.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.
If you must optimize, you may want to consider using a
struct
instead of aclass
if you know that theclass
can be converted to one.struct
s 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.