I guess you hit performance of captured variables in closures · Issue #15276 · JuliaLang/julia · GitHub
Current solution is just to put your closure in let
block
function test(a)
b = a
if a < 0
b = -a
end
let b = b
f(x) = x + b
f(10)
end
end
julia> @code_warntype test(1)
MethodInstance for test(::Int64)
from test(a) in Main at REPL[3]:1
Arguments
#self#::Core.Const(test)
a::Int64
Locals
b@_3::Int64
f::var"#f#4"{Int64}
b@_5::Int64
Body::Int64