On Tue, Aug 4, 2015 at 1:57 PM, Andrew B. Martin
<[email protected]> wrote:
> I'm having a hard time figuring out how to free up memory by zeroing and
> garbage collecting objects in a function.
>
> function runModel()
>     d = generateData()
>     d = 0
>     gc()
> end
>
>
> When I run runModel() in the REPL memory usage remains as if d is still
> stored in memory.
>
> Even if I do:
>
> for i in 1:5
>    d = generateData();
>    d = 0
>    gc()
> end
>
> Memory is not freed by the garbage collection.
>
> If I enter:
>
> julia> d = generateData();
>
> julia> d = 0
>
> julia> gc()
>
> Then memory from d is freed up.
>
> I've looked at this SO question:
> http://stackoverflow.com/questions/25871711/julia-garbage-collection-inside-functions-works-differently-than-in-global-spac
> but it doesn't provide any answers.
>

Short answer:

Don't assume calling gc() can free any specific object and in general,
don't use gc() as a way to free any particular resourse. You will be
better off to be more explicit.

Longer answer:

The lifetime analysis of variables is pretty conservative, and the
effect you see can easily be caused by inlining.

Suppose you have the following functions
```
f() = (a = allocate_something_big(); a)
g() = (b = f(); b = 0; gc())
```

now after inlining, g will look something like

```
function test3()
    a = allocate_something_big()
    b = a
    b = 0
    gc()
end
```

Currently all the local variables are kept alive so the new variables
introduced by inlining can easily keep an object alive unexpectedly.

Also, it's worth noting that calling `gc()` (i.e. `gc(true)`) might
actually make the object live longer due to the promotion to the old
generation that is scanned less frequently.

>
> Why is memory freed when run garbage collection is done in the global scope,
> but not in a function or for-loop?

Reply via email to