Kas saaksite selgitada erinevust virna ja heap mälu vahel?
sobes.tech AI
Vastus AI-lt
Stack and heap are two different memory areas used in C# for data storage, and they differ in management and purpose.
-
Stack — is a memory region where local variables and method parameters are stored. It operates on the LIFO (last in, first out) principle. Memory on the stack is allocated and freed automatically when entering and exiting functions, which is very fast. The stack stores primitive type values and references to objects.
-
Heap — is a memory region for dynamic allocation of objects. When an object is created using
new, memory is allocated on the heap. Memory management on the heap is handled by the Garbage Collector, which frees unused objects. The heap is more flexible, but allocation and deallocation operations are slower than on the stack.
Example:
void Example()
{
int x = 10; // x is stored on the stack
MyClass obj = new MyClass(); // obj is a reference on the stack, the object is on the heap
}
Here, x is a local variable on the stack, and obj is a reference on the stack pointing to an object on the heap.