Defining const inside struct

Parameters output is deceiving, this is actuall abstract type putfall: Performance Tips · The Julia Language

You can avoid it by using parametrized struct

@with_kw struct Options2{T}
   # ... other fields
   seed :: Int64 = 321
   rng :: T = Random.MersenneTwister(seed)
end

and it’s better to test it somewhere where you can see that allocations do not multiply

function f(opts)
    res = 0.
    for i in 1:100
        res += rand(opts.rng)
    end
    return res
end
opt = Options()
opt2 = Options2()

julia> @allocated f(opt)
3200

julia> @allocated f(opt2)
16

Or you can verify that your code is type stable with @code_warntype

julia> @code_warntype f(opt)
Variables
  #self#::Core.Compiler.Const(f, false)
  opts::Options
  res::Any
  @_4::Union{Nothing, Tuple{Int64,Int64}}
  i::Int64

Body::Any
....

julia> @code_warntype f(opt2)
Variables
  #self#::Core.Compiler.Const(f, false)
  opts::Options2{MersenneTwister}
  res::Float64
  @_4::Union{Nothing, Tuple{Int64,Int64}}
  i::Int64

Body::Float64
2 Likes