Memory Management: The Stack & The Heap
Memory Management: The Stack & The Heap
Reference types are placed on the Heap (and on the stack we have a pointer to
them)
Value types
Enums
DateTime
Bool
Char
Example
Reference types
String
Object
String is immutable
StringBuilder is mutable
Memory gets allocated and deallocated to our process all the time
All objects get allocated on this managed heap, but they can have some memory
allocated on the unmanaged heap
Managed vs Un-Managed Memory
Garbage Collector is the part of .NET that allocates and deallocates managed
memory
The unmanaged memory: sockets (for http calls, database access etc), graphics
buffers, streams. This is unmanaged because we need to manage it ourselves:
IDisposable.Dispose()
Memory allocation
Function calls are placed on stack
The Garbage Collector creates a graph of objects starting from roots: static
objects, global objects, local variables
Then the memory gets released, while what remains gets promoted
OutOfMemoryException
Ref & Out
Ref: the value passed is already set, so in the method we can use it and modify it
(the whole instance)
Out: the value passed is not set, so in the method we must set it (and not use it)
Serialization / Deserialization
Serialization: preparing the object so we can send it over the wire (network)
● Binary serialization
● Text serialization: xml, json, google protobuf