# Weird allocations

**URL:** <https://discourse.julialang.org/t/weird-allocations/47267>\
**Category:** General Usage\
**Tags:** question, memory-allocation\
**Created:** [September 25, 2020, 2:43pm UTC](https://discourse.julialang.org/t/weird-allocations/47267 "2020-09-25T14:43:51Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mikkoku](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mikkoku/32/16274_2.png) [@mikkoku](https://discourse.julialang.org/u/mikkoku)\
**Post date:** [September 25, 2020, 2:43pm UTC](https://discourse.julialang.org/t/weird-allocations/47267/1 "2020-09-25T14:43:51Z")

</div>

I was working some numeric integration stuff when I encountered a lot of small allocations for which I couldn’t find a source for.

Here is a MWE demonstrating the behaviour

```julia
function f1(f, x)
    s = 0.0
    for i in 1:2
        s += f(x)
    end
    s
end
function f2(f, x)
    s = 0.0
    for j in 1:100
        s += f1(f, x)
    end
    s
end

g(x) = @fastmath sqrt(x)
@time f1(g, 1.0)
# no allocations

@time f2(g, 1.0)
# 300 allocations, 4800 bytes

@noinline g2(x) = x
@time f2(g2, 1.0)
# no allocations

```

Looking at `@code_native` didn’t give any reason to expect allocations.

Although this was not a problem for performance I would really appreciate if someone could explain these allocations.

---

<div class="post-metadata">

**Author:** ![lucas711642](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lucas711642/32/12051_2.png) [@lucas711642](https://discourse.julialang.org/u/lucas711642)\
**Post date:** [September 25, 2020, 2:51pm UTC](https://discourse.julialang.org/t/weird-allocations/47267/2 "2020-09-25T14:51:53Z")

</div>

The compiler is not specializing `f` in `f2`. This solves the problem:

```julia
function f2(f::F, x) where F
    s = 0.0
    for j in 1:100
        s += f1(f, x)
    end
    s
end

```

---

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [September 25, 2020, 2:55pm UTC](https://discourse.julialang.org/t/weird-allocations/47267/3 "2020-09-25T14:55:27Z")

</div>

See also: [Performance Tips · The Julia Language](https://docs.julialang.org/en/v1/manual/performance-tips/#Be-aware-of-when-Julia-avoids-specializing)
