# Let expression and garbage collection

**URL:** <https://discourse.julialang.org/t/let-expression-and-garbage-collection/7804>\
**Category:** General Usage\
**Created:** [December 16, 2017, 8:27am UTC](https://discourse.julialang.org/t/let-expression-and-garbage-collection/7804 "2017-12-16T08:27:57Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jw3126](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jw3126/32/3086_2.png) [@jw3126](https://discourse.julialang.org/u/jw3126)\
**Post date:** [December 16, 2017, 8:27am UTC](https://discourse.julialang.org/t/let-expression-and-garbage-collection/7804/1 "2017-12-16T08:27:57Z")

</div>

Not sure if this is a bug, or if I misunderstand something about `let`. But  
I think in the following snipped `ret` is unreachable, when `gc()` runs, yet it does not get collected.

```julia
function f end
let
    ret = []
    finalizer(ret, println)
    f() = ret
end

f()
f() = "something else"
f()
gc()

```

---

<div class="post-metadata">

**Author:** ![ihnorton](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ihnorton/32/26_2.png) [@ihnorton](https://discourse.julialang.org/u/ihnorton)\
**Post date:** [December 17, 2017, 5:15am UTC](https://discourse.julialang.org/t/let-expression-and-garbage-collection/7804/2 "2017-12-17T05:15:43Z")

</div>

It’s not an issue with `let`:

```julia
julia> let ret = Ref(0)
         finalizer(ret, println)
         global f = ret
       end
Base.RefValue{Int64}(0)

julia> f
Base.RefValue{Int64}(0)

julia> f = 0
0

julia> gc()
Base.RefValue{Int64}(0)

```

I believe the issue is approximately that Julia doesn’t GC methods, merely updates the method table (ref [11695](https://github.com/JuliaLang/julia/issues/11695), but that’s only talking about object code specifically). You may have noticed that the finalizer does run when you cleanly exit Julia.

However, this doesn’t quite make sense in a few test cases I tried because the AST only appears to be storing a literal.

(by the way: `finalizer` should not cause a task switch, such as by performing I/O, but this was not documented – see [https://github.com/JuliaLang/julia/pull/25141](https://github.com/JuliaLang/julia/pull/25141) for workarounds)

---

<div class="post-metadata">

**Author:** ![jw3126](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jw3126/32/3086_2.png) [@jw3126](https://discourse.julialang.org/u/jw3126)\
**Post date:** [December 19, 2017, 8:48pm UTC](https://discourse.julialang.org/t/let-expression-and-garbage-collection/7804/3 "2017-12-19T20:48:52Z")

</div>

Thanks! What I really want to do is having a function with a few methods and each method should have some private state. If a method gets overwritten, the state should be garbage collected (or at least some `empty!` like function should run on it. The application I have in mind is memoization. Is there currently a way to do this?
