Can the compiler sometimes optimize small unions to avoid boxing?

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:) (More Info)

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.

2 Likes