How does R's garbage collection work and when would you call gc()?

Quick Overview

Asks how garbage collection works in R and when a manual gc() call is worth making. Tests whether you understand reachability, the generational mark-and-sweep collector, what an explicit call changes, and better ways to control memory use in R code.

How does R's garbage collection work and when would you call gc()?

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Other

How does R's garbage collection work and when would you call `gc()`? ```hint Reachability Think about what makes an R object unreachable, including objects still held by environments and closures, and what R already does on its own when it needs memory. ``` ```hint What a manual call changes Compare what happens with and without an explicit `gc()` call after removing a large object. Ask what the call changes besides timing. ``` ### What a Strong Answer Covers - How R decides an object can be freed and when collection runs automatically - The generational mark-and-sweep design and why generations help - What a manual `gc()` call does and does not achieve - Legitimate reasons to call `gc()`, such as reading memory usage or releasing external resources - Practices that reduce memory use more effectively than calling `gc()` ### Follow-up Questions - Why can an object stay in memory after you remove every variable you know points to it? - How does copy-on-modify affect peak memory, and how would you find unexpected copies? - How would you measure how much memory a function allocates? - Before forking workers with `parallel::mclapply`, why might you remove large objects first?

Overview: Asks how garbage collection works in R and when a manual gc() call is worth making. Tests whether you understand reachability, the generational mark-and-sweep collector, what an explicit call changes, and better ways to control memory use in R code.

Nov 24, 2026
mediumData ScientistOtherData Manipulation (SQL/Python)
0
0

How does R's garbage collection work and when would you call gc()?

What a Strong Answer Covers Guidance

  • How R decides an object can be freed and when collection runs automatically
  • The generational mark-and-sweep design and why generations help
  • What a manual gc() call does and does not achieve
  • Legitimate reasons to call gc() , such as reading memory usage or releasing external resources
  • Practices that reduce memory use more effectively than calling gc()

Follow-up Questions Guidance

  • Why can an object stay in memory after you remove every variable you know points to it?
  • How does copy-on-modify affect peak memory, and how would you find unexpected copies?
  • How would you measure how much memory a function allocates?
  • Before forking workers with parallel::mclapply , why might you remove large objects first?