7 ms·
So, I'm not sure what the situation is with Java, but I suspect there might be some confusion in what you're reading. In C#, anything instantiated as part of a
by Kapura 9y ago
So, I'm not sure what the situation is with Java, but I suspect there might be some confusion in what you're reading.
In C#, anything instantiated as part of a class goes onto the heap. Value types that are declared and used only within the function are allocated onto the stack. For example:
public class Example
{
public int a; // Allocated onto the heap when Example is instanced
public int b; // Allocated onto the heap when Example is instanced
public int c; // Allocated onto the heap when Example is instanced
public void CycleValues()
{
int temp = a; // Allocated onto the stack when function is called
a = b; // a, b, and c are already allocated
b = c;
c = temp;
// temp goes away when the function finishes executing
}
public int SumPositiveValues()
{
List<int> positiveList = new List(); // Not a value type: allocates onto the heap
if (a > 0)
valueList.Add(a);
if (b > 0)
valueList.Add(b);
if (c > 0)
valueList.Add(c);
int sum = 0; // Allocated onto the stack
foreach (int i in valueList)
{
sum += i;
}
return sum;
// sum goes away when the function finishes executing
// positiveList was allocated onto the heap, so it persists (although inaccessible) until garbage collection
}
}
In the example above, space on the heap is allocated when you create a new Example(). Calling CycleValues() doesn't allocate anything new onto the heap, so it isn't creating any garbage. Calling SumPositiveValues() creates a new List(), which, not being a value type, is allocated onto the heap. When the function finishes, that memory isn't automatically freed; it creates garbage. Optimising for heap performance relies a lot on removing New calls to classes when it is possible and makes sense to do so.
- merb 9y agowell thats what I meant. Basically I'm not a game dev, but keeping simple values on the stack is most often not a problem. However it's insane how many Lists, Arrays I need and I'm a web developer. So I guess a Game Dev even needs more of these (Inventory, Stats, Chat, whatever)
- Kapura 9y agoYeah, but the big key is to keep things instantiated only once (where reasonable). So, if I'm making an RTS, I keep only one list of selected units, and it persists even if I have no units selected. No reallocation or losing the reference means nothing is getting garbage collected. There are bigger convos to be had about data architecture here, but now's neither time nor place for it.