When to use mutable structs?

@jameson (hope I’ve got the username right, apologies if not!) I think we were getting a bit off-topic in Ref docstring should note clearly that it's an abstract type · Issue #55321 · JuliaLang/julia · GitHub.

You’ve said there

Users that want a mutable field should be using mutable since it is much faster than RefValue.

and replied to this

@vtjnash could you clarify this please? I thought the general performance advice is “use an immutable struct instead of a mutable struct”. If I have some gigantic struct with 100 fields, and 99 of those can be immutable but the 100’th is a Bool I want to be able to toggle between true/false, your statement implies that I should use a mutable struct but I would find that surprising!

with

Yes, a mutable struct would probably be much better there most of the time, even if only because of the number of constant fields. The general advice is wrong, since it only applies to specific cases (albeit frequent cases, it is not general)

I think for me, it would be helpful if you could contribute some explanation of this mutable vs. immutable issue to the docs under Types · The Julia Language. The cryptic statement there is

In cases where one or more fields of an otherwise mutable struct is known to be immutable, one can declare these fields as such using const as shown below. This enables some, but not all of the optimizations of immutable structs, and can be used to enforce invariants on the particular fields marked as const.

Some explanation of what the cases are when there is a performance benefit from immutable structs, and when it is better to use a mutable struct would be very helpful. As a user, I don’t understand from the documentation when or why to use one or the other, so I’d tend to fall back to “I’d better use an immutable struct if I possibly can, because otherwise there might be performance penalties to using mutable struct in some cases and I don’t understand what those cases are, or if mine is one of them”. At least some discussion of the “frequent cases” you mention would be helpful!

1 Like

I mostly use mutable structs, an immutable structs only for very small structs. I work a lot with SVectors and MVectors. Sometimes you need to use an SVector to avoid allocations, but most of the time MVectors are fine.

OK, vectors aren’t structs, but the the difference between mutable and immutable should be similar.

If you have a struct that is mostly immutable, but you need to change one or a few fields, you can also use Getting started · Accessors.jl