Enum type as field value performance

I know it is discouraged to use an abstract type for a field in a composite type due to the runtime overhead of looking up the type and method resolution.

Does using an enum type suffer from the same problem? Or is it more performant.

Example:

abstract type Side end
struct Bid <: Side end
struct Ask <: Side end

struct Trade
    ...
    s::Side
end

vs

@enum Side bid ask

struct Trade
    ...
    s::Side
end

Note: in the first code snippet I know I could use a type parameter, but that would lead to type instabilities elsewhere for me

The enum is much more performant. Internally, a Julia enum is just an integer with a restricted set of values enforced at instantiation, and some names attached to each value.
You can even make the enum a custom size, i.e. if you know for sure you only need at most 256 variants, you can do @enum Side::UInt8 bid ask, and it’ll be 1 byte in size.

3 Likes