c# – Why do you need a bunch?

Question:

I understand that the stack is temporary, while it is stored in the scope {}, value types are stored on the stack, and the variable contains its address on the stack, reference types store on the stack a reference to the heap in which the object is contained.
But why not leave one thing alone? Yes, the stack is only 1MB, but why couldn't it be expanded?
What are the advantages of this approach and why was it worth creating such a division?
Naturally, I searched, but little by little answers.

Answer:

For starters, the heap, like the stack, is an implementation detail. The language standard does not mandate the use of the heap for storing objects.

The Microsoft implementation of C # uses the heap because it is convenient to host long-lived objects.

No matter how big the stack is, it works in such a way that when the function finishes, the objects allocated on the stack die. Therefore, if the lifetime of an object exceeds (or potentially exceeds) the execution time of the function that created it, the stack for such an object is not suitable.

Worse, an object can only be released from the stack after all previous objects have been deallocated. This means that in the code

string f()
{
    StringBuilder sb = new StringBuilder();
    // цикл заполнения
    string s = sb.ToString();
    return s;
}

the sb object, which is created before the string object, will be on the stack, and cannot be freed as long as the caller needs the s object!


Of the two entities – the heap and the stack – it is easier to get rid of the stack , and allocate all objects on the heap. The language standard does not prescribe that stack objects must die along with the stack frame (the language standard does not mention the stack at all), so if such objects are eaten sometime later by the garbage collector, nothing terrible will happen. But this is less efficient than placing variables on the stack, since it increases the load on the garbage collector.

Scroll to Top