# Mysterious allocation in function returning Union type

**URL:** <https://discourse.julialang.org/t/mysterious-allocation-in-function-returning-union-type/88189>\
**Category:** Performance\
**Tags:** memory-allocation\
**Created:** [October 3, 2022, 8:58pm UTC](https://discourse.julialang.org/t/mysterious-allocation-in-function-returning-union-type/88189 "2022-10-03T20:58:08Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![matthias314](https://avatars.discourse-cdn.com/v4/letter/m/a88e4f/32.png) [@matthias314](https://discourse.julialang.org/u/matthias314)\
**Post date:** [October 3, 2022, 8:58pm UTC](https://discourse.julialang.org/t/mysterious-allocation-in-function-returning-union-type/88189/1 "2022-10-03T20:58:08Z")

</div>

I’m looking at functions with return type `Union{T,Nothing}` for some concrete type `T`. Most of the time they don’t allocate. But where does the allocation in `f(a1, nothing)` in the code below come from? Is there a way to avoid it while keeping the return type of `f` as a Union type?

```julia
struct A{T}
    x::T
end

f(a, b) = iszero(a.x) ? b : a
g(a, b) = iszero(a) ? b : a

a0 = A([0,0])
a1 = A([1,1])
c1 = A(1)
v1 = [1,1]

@ballocated f($a1, nothing) # 16
@ballocated f($a0, nothing) # 0
@ballocated f($a1, $a0) # 0
@ballocated f($c1, nothing) # 0
@ballocated g($v1, nothing) # 0

```

I’m using Julia 1.8.2.

---

<div class="post-metadata">

**Author:** ![Dan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dan/32/42581_2.png) [@Dan](https://discourse.julialang.org/u/Dan)\
**Post date:** [October 4, 2022, 1:04am UTC](https://discourse.julialang.org/t/mysterious-allocation-in-function-returning-union-type/88189/2 "2022-10-04T01:04:24Z")

</div>

Note that if you remove the interpolation, the allocation goes back down to 0

```julia
@ballocated f(a1, nothing) # 0 !!

```

---

<div class="post-metadata">

**Author:** ![matthias314](https://avatars.discourse-cdn.com/v4/letter/m/a88e4f/32.png) [@matthias314](https://discourse.julialang.org/u/matthias314)\
**Post date:** [October 4, 2022, 1:34am UTC](https://discourse.julialang.org/t/mysterious-allocation-in-function-returning-union-type/88189/3 "2022-10-04T01:34:10Z")

</div>

Are you sure? On my machine, `@ballocated f(a1, nothing)` also gives `16`.

---

<div class="post-metadata">

**Author:** ![Dan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dan/32/42581_2.png) [@Dan](https://discourse.julialang.org/u/Dan)\
**Post date:** [October 4, 2022, 1:48am UTC](https://discourse.julialang.org/t/mysterious-allocation-in-function-returning-union-type/88189/4 "2022-10-04T01:48:40Z")

</div>

Ah, you are right. I also defined `a1` as a const-type global:

```julia
a1::A{Vector{Int}} = A([1,1])

```

and then it went to 0
