# How to avoid the 2 allocations for any struct?

**URL:** https://discourse.julialang.org/t/how-to-avoid-the-2-allocations-for-any-struct/24590
**Category:** New to Julia
**Created:** [May 24, 2019, 9:50pm UTC](https://discourse.julialang.org/t/how-to-avoid-the-2-allocations-for-any-struct/24590 "2019-05-24T21:50:33Z")
**Posts on this page:** 2
**Page:** 2

<div class="post-metadata">

### Author: ![Jean\_Michel](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jean_michel/32/8282_2.png) [@Jean\_Michel](https://discourse.julialang.org/u/Jean_Michel)
#### Post date: [May 26, 2019, 8:31am UTC](https://discourse.julialang.org/t/how-to-avoid-the-2-allocations-for-any-struct/24590/21 "2019-05-26T08:31:26Z")

</div>

Do not attribute the confusion to me. If you look at my message (the very first one in this thread)  
I was just asking if there is a way to avoid the cost, allocation-wise, of doing things the proper way that you point out.

---

<div class="post-metadata">

### Author: ![hckr](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/hckr/32/4836_2.png) [@hckr](https://discourse.julialang.org/u/hckr)
#### Post date: [May 26, 2019, 10:15am UTC](https://discourse.julialang.org/t/how-to-avoid-the-2-allocations-for-any-struct/24590/22 "2019-05-26T10:15:03Z")

</div>

Your function that extends `*` annotated with `@inline`.

```julia
@inline function Base.:*(a::Perm,b::Perm)
    r=similar(a.d)
    @inbounds for (i,v) in enumerate(a.d) r[i]=b.d[v] end
    Perm(r)
end

```

Another function that uses extended `*`.

```julia
function foo(pa, b)
    sum((a*b).d)
end

```

It is optimized out with inlinining as suggested by @yuyichao.

```julia
julia> @btime foo($pa, $pb)
27.091 ns (1 allocation: 128 bytes)

```

It appears, though, `@inline` seems necessary for this context for no extra allocation. I am on Julia 1.1.0.

This SO question may be relevant to your inquiry. Note that your struct is immutable but not `isbits`-immutable.  
[https://stackoverflow.com/questions/43932741/stack-allocation-of-isbits-types-in-julia](https://stackoverflow.com/questions/43932741/stack-allocation-of-isbits-types-in-julia)

[Previous page](https://discourse.julialang.org/t/how-to-avoid-the-2-allocations-for-any-struct/24590.md?page=1)
