I have a complex algorithm that works with 30+ GB of memory, and I need to optimize it because I'm getting System.OutOfMemory exception sometimes.
For example, imagine this code:
public void DoWork()
{
HashSet<MyStruct> hashSet = LoadALotOfStructs();
List<MyStruct> list = hashSet.ToList();
// Lot of code that can not use the hashSet anymore
}
Now, since I will never use the HashSet again, I want to tell GC to get rid of the HashSet and free memory immediately. So, I am wondering about this simple change:
public void DoWork()
{
List<MyStruct> list;
{ // just this
HashSet<MyStruct> hashSet = LoadALotOfStructs();
list = hashSet.ToList();
} // and this
// Lot of code that can not use the hashSet anymore
}
Can this be done? Does the GC clean the objects instantiated inside the { } block when they get out of context?
Also, keep in mind that this is just an example that illustrates my question, the code is very different.