# Understanding allocations when collapsing function arugments

**URL:** <https://discourse.julialang.org/t/understanding-allocations-when-collapsing-function-arugments/59668>\
**Category:** General Usage\
**Created:** [April 20, 2021, 2:14pm UTC](https://discourse.julialang.org/t/understanding-allocations-when-collapsing-function-arugments/59668 "2021-04-20T14:14:20Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [April 20, 2021, 2:42pm UTC](https://discourse.julialang.org/t/understanding-allocations-when-collapsing-function-arugments/59668/6 "2021-04-20T14:42:54Z")

</div>

> [@bashonubuntu](#):
>
> The allocation issue persists even when timed inside `main()`

Yes, this is a tricky thing. I guess you mean something like:

```julia
julia> function main(x)
         g(x,z) = x + z
         f(x) = g(x,y)
         y = 2
         f(x)
       end
main (generic function with 1 method)

julia> @btime main(1)
  20.894 ns (1 allocation: 16 bytes)
3

```

This is confusing and there are other discussion whether that should raise an error, a warning, or something else. The problem is that there is an ambiguity on whether `y` is a constant in the local scope, if it can vary, and that apparently is making the compiler make bad choices (outside my scope of understanding).

The safe alternative is being more explicit on what one wants:

```julia
julia> function main(x)
         g(x,y) = x + y
         f(x,inner_g) = inner_g(x)
         y = 2
         f(x, x -> g(x,y))
       end
main (generic function with 1 method)

julia> @btime main(1)
  0.025 ns (0 allocations: 0 bytes)
3

```

But with a lot of different parameters, I would play even safer and use a struct:

```julia
julia> struct Params
         y::Int
       end
       function main(x)
         g(x,y) = x + y 
         f(x,p) = g(x,p.y)
         p = Params(2)
         f(x,p)
       end
main (generic function with 1 method)

julia> @btime main(1)
  0.023 ns (0 allocations: 0 bytes)
3

```

I just opened another thread with a related issue: [Performance closures with changing value of closed over variables](https://discourse.julialang.org/t/performance-closures-with-changing-value-of-closed-over-variables/59671)

---

_[View the full topic](https://discourse.julialang.org/t/understanding-allocations-when-collapsing-function-arugments/59668)._
