Stream: beginners

Topic: Limits of refcounting optimizations


view this post on Zulip Joshua Warner (Dec 28 2022 at 03:12):

I have the following code, and I'm wondering whether the way I'm bundling state together into this IdBindState record is going to be negating the optimization where a refcount of 1 allows in-place mutation?

IdBindState : { byId: List IdParser, byName: Dict Name Id, unique: Dict Str Id }

stateBind : IdBindState, IdParser -> {state: IdBindState, id: Id}
stateBind = \state, parser ->
    when Dict.get state.unique parser is
        Err KeyNotFound ->
            id = List.len state.byId
            newById = List.append state.byId parser
            newUnique = Dict.set state.unique parser id
            {state: {byId: newById, byName: state.byName, unique: newUnique}, id}
        Ok id -> {state, id}

In particular - will the old versions of byId and unique be kept alive because they're still referenced from state? Or will the compiler know that each of those fields in that particular state is ever accessed again?

If the compiler doesn't optimize that reliably, I can see that being a footgun of accidental state duplication.

view this post on Zulip Brendan Hansknecht (Dec 28 2022 at 04:44):

Currently a foot gun

view this post on Zulip Brendan Hansknecht (Dec 28 2022 at 04:45):

Has been noted a few times before.

view this post on Zulip Brendan Hansknecht (Dec 28 2022 at 04:46):

I always deconstruct records that are function inputs to avoid that issue


Last updated: Jul 06 2025 at 12:14 UTC