Sunday, July 29, 2018

c# - Allocated on the heap or the stack?




I recently asked a question about StackOverflowExeptions and the explanations were very helpful!
However, I wrote a method and tried to figure out where T cached is allocated (heap/stack):




private Dictionary _cachedComponents = new Dictionary();

public T GetCachedComponent() where T : Component {
//Not yet sure if the next line works or throws an exception -> just ignore it
if(_cachedComponents[typeof(T)] != null) {
return (T)_cachedComponents[typeof(T)]
} else {
T cached = this.GetComponent();
_cachedComponents.Add(typeof(T), cached);

return cached;
}
}



  1. Since T cached is declared inside the method I assume it is allocated on the stack, right?

  2. But the reference is then added to the dictionary, wich should be allocated on the heap, right?

  3. The stack is "cleared" after the method returns, right?

  4. But what happens to T cached?
    Is it going to be moved to the heap?
    (Because the stack does not "carry the data" anymore but the dictionary still holds a reference)



Answer




Since T cached is declared inside the method I assume it is allocated
on the stack, right?




T being allocated in a method doesn't effect it being on the heap or the stack. The decision whether it is the former or the latter is based on whether this is a reference type or a value type.





But the reference is then added to the dictionary, wich should be
allocated on the heap, right?




Once the reference is added to the Dictionary, the key will be stored inside the dictionary, which is allocated on the heap, as it is a reference type.




The stack is "cleared" after the method returns, right?





The stack frame is cleared once the method returns.




But what happens to T cached? Is it going to be moved to the heap?




If T is cached inside the dictionary, then it is already allocated on the heap.



Overall, I assume you ask these questions as for general knowledge. You shouldn't be worrying about this too much, as what I wrote here is an implementation detail and is subject to change.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...