Every program must answer one question: when to free the allocated memory. There are three common approaches, and each involves sacrificing something different.
Automatic trash collection
The program should continue to distribute resources freely; periodically, the collection team should survey the area to see which zones are no longer being claimed and then reclaim them.
- Pros: Programmers hardly have to think about it, and there are no errors related to using freed memory
- Cons: unpredictable pauses when the garbage collector runs, and higher RAM usage than necessary
Suitable for server services and business applications—where throughput is more important than maximum latency.
Reference Counting
Each object has a counter. Adding a reference increments the counter; removing a reference decrements it; when it reaches 0, the object is immediately freed.
- Pros: Released at the right time, no unexpected pauses
- Cons: incurs a cost each time an assignment is made, and cannot handle reference cycles on its own — if A holds B and B holds A, neither will ever be set to 0
Ownership and Borrowing
The compiler tracks who owns each memory region and inserts release instructions in the right places during compilation. There is no garbage collector, no counters, and no overhead at runtime.
- Pros: Fast and predictable, just like manual management, but secure
- Cons: Writers must learn a new way of thinking, and some data structures become difficult to express
There is no surefire way to win
Real-time systems and embedded software opt for the third approach because any delay is unacceptable. Web applications opt for the first approach because saving human time is more important than a few dozen milliseconds. Both are correct in their respective contexts.
Thảo luận