How is memory managed in Swift compared to Kotlin or Java?
LanguagesMid-level
In shortSwift uses Automatic Reference Counting, which frees an object as soon as its last strong reference goes away. Kotlin on the JVM and Java use a garbage collector that periodically frees unreachable objects.
Model answer
Swift: Automatic Reference Counting (ARC). The compiler inserts retain and release calls. Every class instance counts its strong references, and when the count reaches zero it is freed right away. Memory use is predictable and there are no collection pauses.
The weak spot is retain cycles: if two objects reference each other strongly, neither count reaches zero. You break the cycle with weak (becomes nil when the object is freed) or unowned (assumed to always exist), most often as [weak self] in closures.
Kotlin and Java: garbage collection. The JVM (or Android’s ART) periodically starts from roots such as threads and static fields and frees everything it can’t reach. Cycles are not a problem, because unreachable cycles are collected too. The cost is that collection runs when the runtime decides, which can mean short pauses and more memory headroom.
| ARC (Swift) | GC (JVM, ART) | |
|---|---|---|
| When memory is freed | Immediately at zero references | When the collector runs |
| Reference cycles | Leak unless broken with weak | Collected automatically |
| Runtime cost | Small, spread across every assignment | Periodic, can cause pauses |
A good closing line: “Both are automatic, but with ARC I still have to think about ownership; with a GC I think more about allocation pressure and pause times.”
What they're looking for
That you know both models, the trade-off between predictability and convenience, and the retain cycle problem that only ARC has.
Common mistakes
- Saying Swift has a garbage collector.
- Not mentioning retain cycles and how weak or unowned references fix them.
- Claiming garbage collection has no cost.
More languages questions
- What is the difference between a value type and a reference type?Junior
- What is the difference between checked and unchecked exceptions, and how do Kotlin and Swift handle this?Mid-level
- What are type erasure and variance in generics, and how do Swift, Kotlin and Java differ?Senior
- When would you choose composition over inheritance?Mid-level