Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between gc() and rm()

I am periodically cleaning the memory in R using a call to rm(list=ls()).
Do I need to call the garbage collector gc() after that?

What is the difference between these 2 functions? Does gc() call rm() for certain variables?

like image 388
RockScience Avatar asked Jan 11 '12 03:01

RockScience


People also ask

What does GC () do in R?

R uses an alternative approach: garbage collection (or GC for short). GC automatically releases memory when an object is no longer used. It does this by tracking how many names point to each object, and when there are no names pointing to an object, it deletes that object.

What is the function of GC ()?

gc() method runs the garbage collector. Calling this suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse.

What is the difference between garbage collection and?

The difference between the garbage collector and destructor is that a garbage collector is a software that performs automatic memory management while a destructor is a special method called by the garbage collector during the destruction of the object.

What is RM function in R?

rm() function in R Language is used to delete objects from the memory. It can be used with ls() function to delete all objects.


1 Answers

First, it is important to note that the two are very different in that gc does not delete any variables that you are still using- it only frees up the memory for ones that you no longer have access to (whether removed using rm() or, say, created in a function that has since returned). Running gc() will never make you lose variables.

The question of whether you should call gc() after calling rm(), though, is a good one. The documentation for gc helpfully notes:

A call of gc causes a garbage collection to take place. This will also take place automatically without user intervention, and the primary purpose of calling gc is for the report on memory usage.

However, it can be useful to call gc after a large object has been removed, as this may prompt R to return memory to the operating system.

So the answer is that it can be good to call gc() (and at the very least, can't hurt), even though it would likely be triggered anyway (if not right away, then soon).

like image 122
David Robinson Avatar answered Sep 28 '22 09:09

David Robinson