Skip to content
Commitwise
Menu

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 freedImmediately at zero referencesWhen the collector runs
Reference cyclesLeak unless broken with weakCollected automatically
Runtime costSmall, spread across every assignmentPeriodic, 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

Esc

Type to search the whole site.