Middle
What is the difference between a garbage collector and automatic memory management (ARC)?
sobes.tech AI
Answer from AI
Garbage collector automatically finds and frees memory that is no longer used by the program. It runs in the background, periodically scanning the heap and identifying objects that have no active references.
ARC (Automatic Reference Counting) in Swift and Objective-C manages the lifecycle of objects by counting the number of strong references to each object. When the count of strong references to an object drops to zero, ARC automatically frees the memory occupied by that object.
Main differences:
| Feature | Garbage Collector | ARC |
|---|---|---|
| Principle of operation | Finds unreachable objects | Counts strong references |
| Moment of release | Non-deterministic, during scanning | Deterministic, at zero references |
| Overhead | Pauses in program execution (during collection) | Minimal, during reference count changes |
| Predictability | Low | High |
| Cyclic references | Require special handling (e.g., weak references) | Require use of weak or unowned references |
| Usage in iOS | Not present in modern Objective-C and Swift | Main memory management mechanism in Objective-C and Swift |
Example of using weak to prevent strong reference cycles in ARC:
class Person {
let name: String
var apartment: Apartment? // strong reference
init(name: String) {
self.name = name
print("\(name) is being initialized")
}
deinit {
print("\(name) is being deinitialized")
}
}
class Apartment {
let unit: String
weak var tenant: Person? // weak reference
init(unit: String) {
self.unit = unit
print("Apartment \(unit) is being initialized")
}
deinit {
print("Apartment \(unit) is being deinitialized")
}
}
var john: Person?
var unit4A: Apartment?
john = Person(name: "John Appleseed")
unit4A = Apartment(unit: "4A")
john!.apartment = unit4A
unit4A!.tenant = john // weak reference prevents retain cycle
john = nil // Person object is deinitialized
unit4A = nil // Apartment object is deinitialized