# Can the compiler sometimes optimize small unions to avoid boxing?

**URL:** <https://discourse.julialang.org/t/can-the-compiler-sometimes-optimize-small-unions-to-avoid-boxing/56028>\
**Category:** General Usage\
**Tags:** performance\
**Created:** [February 25, 2021, 4:41pm UTC](https://discourse.julialang.org/t/can-the-compiler-sometimes-optimize-small-unions-to-avoid-boxing/56028 "2021-02-25T16:41:47Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![BridgeBot](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bridgebot/32/21491_2.png) [@BridgeBot](https://discourse.julialang.org/u/BridgeBot)\
**Post date:** [February 25, 2021, 4:41pm UTC](https://discourse.julialang.org/t/can-the-compiler-sometimes-optimize-small-unions-to-avoid-boxing/56028/1 "2021-02-25T16:41:47Z")

</div>

Hi, random question about performance: can the compiler sometimes optimize Union type variables so that there is no boxing or unboxing? For example, if I declare an “optional” integer type like `Union{Nothing, Int}`would the compiler be smart enough to keep that on the stack?

Note that the original poster on Slack cannot see your response here on Discourse. Consider _transcribing the appropriate answer back to Slack_, or pinging the poster here on Discourse so they can _follow this thread_.  
[(Original message :slack:)](https://julialang.slack.com/archives/C6A044SQH/p1614271261386600?thread_ts=1614271261.386600&cid=C6A044SQH) [(More Info)](https://github.com/JuliaCommunity/SlackBridge)

---

<div class="post-metadata">

**Author:** ![mbauman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mbauman/32/31082_2.png) [@mbauman](https://discourse.julialang.org/u/mbauman)\
**Post date:** [February 25, 2021, 4:46pm UTC](https://discourse.julialang.org/t/can-the-compiler-sometimes-optimize-small-unions-to-avoid-boxing/56028/2 "2021-02-25T16:46:03Z")

</div>

Yes, if the small union is type-stable and compiled, then this is guaranteed. It’s actually what powers iteration — so it _really_ needs to be fast — and is why small unions like these are flagged in yellow by `@code_warntype` instead of red. The compiler just drops this down to a simple `if` statement with two unboxed branches.
