#What's the most performant way to reset a mutable struct to its initial state

1 messages · Page 1 of 1 (latest)

lost sluice
#

I'm implementing a reinforcement learning trading system that requires frequent state resets between episodes. Given that my simulation runs many episodes with multiple trading steps each, I want to avoid object allocation overhead from creating new state instances.

Is there a more idiomatic way to reset a mutable struct to its initial values that's performant and doesn't require me to maintain two separate pieces of code -- the struct itself, and the reset function?

@kwdef mutable struct TradingState
    balance::Float64 = 1000.0
    position::Position = LONG
    shares::Int = 0
end

const INITIAL_STATE = TradingState()

function reset!(state::TradingState)
    state.balance = INITIAL_STATE.balance
    state.position = INITIAL_STATE.position
    state.shares = INITIAL_STATE.shares
end
sullen junco
#

I think this is fine, though another way maybe is to bring out all the constants into the top of the file and then reference them maybe

sullen junco
#

Basically like this ```julia
const INITIAL_STATE = (balance=1000.0, position=LONG, shares=0)

@kwdef mutable struct TradingState
balance::Float64 = INITIAL_STATE.balance
position::Position = INITIAL_STATE.position
shares::Int = INITIAL_STATE.shares
end

function reset!(state::TradingState)
state.balance = INITIAL_STATE.balance
state.position = INITIAL_STATE.position
state.shares = INITIAL_STATE.shares
end```