`Core.Box` around captured variable

If I define a variable inside an outer function that generates a closure, this variable gets boxed inside the closer. Does this affect performance and if yes, how do I best avoid it?

Here is a simple MWE:

julia> function Adder(a)
           ncalled = 0
           function f(b)
               ncalled += 1
               @info "calling this adder for the $ncalled time"
               return a + b
           end
           return f
       end

julia> plus1 = Adder(1)
(::var"#adder#1"{Int64}) (generic function with 1 method)

julia> plus1.a
1

julia> plus1.ncalled
Core.Box(0)

That’s unfortunately a known issue

You can fix it by using a let

function f(a)
     g = let a=a
         function g(b)
              a + b
          end
      end
end

I’m on my phone, sorry for brevity

1 Like

Ah, I thought that let should be the solution but didn’t know how exactly it went. Thanks!

1 Like