# Unwanted allocations calling function stored in structure

**URL:** <https://discourse.julialang.org/t/unwanted-allocations-calling-function-stored-in-structure/6014>\
**Category:** General Usage\
**Created:** [September 21, 2017, 12:52am UTC](https://discourse.julialang.org/t/unwanted-allocations-calling-function-stored-in-structure/6014 "2017-09-21T00:52:32Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![cstook](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cstook/32/3731_2.png) [@cstook](https://discourse.julialang.org/u/cstook)\
**Post date:** [September 21, 2017, 12:52am UTC](https://discourse.julialang.org/t/unwanted-allocations-calling-function-stored-in-structure/6014/1 "2017-09-21T00:52:32Z")

</div>

Below is a toy example of my problem. The call `b.f(1.0)` allocates memory. Is it possible to call the function h inside FunctionHolder without allocations?

```julia
struct FunctionHolder
    f :: Function
end

function main()
    g(x) = x+1
    a = FunctionHolder(g)
    @time g(1)
    @time a.f(1)

    h(x) = x+1.0
    b = FunctionHolder(h)
    @time h(1.0)
    @time b.f(1.0) # why allocation here?
end

main()
main()

```

Produces the following output.

```julia
0.000000 seconds
0.001330 seconds (11 allocations: 880 bytes)
0.000000 seconds
0.001294 seconds (13 allocations: 992 bytes)
0.000000 seconds
0.000001 seconds
0.000000 seconds
0.000001 seconds (1 allocation: 16 bytes)

```

---

<div class="post-metadata">

**Author:** ![ChrisRackauckas](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chrisrackauckas/32/77_2.png) [@ChrisRackauckas](https://discourse.julialang.org/u/ChrisRackauckas)\
**Post date:** [September 21, 2017, 1:27am UTC](https://discourse.julialang.org/t/unwanted-allocations-calling-function-stored-in-structure/6014/2 "2017-09-21T01:27:46Z")

</div>

This is expected. `Function` is an abstract type. This is the same issue as always with a field of an abstract type. For strict typing,

```julia
struct FunctionHolder{F}
    f :: F
end

```

---

<div class="post-metadata">

**Author:** ![cstook](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cstook/32/3731_2.png) [@cstook](https://discourse.julialang.org/u/cstook)\
**Post date:** [September 21, 2017, 1:29am UTC](https://discourse.julialang.org/t/unwanted-allocations-calling-function-stored-in-structure/6014/3 "2017-09-21T01:29:17Z")

</div>

Thank you!
