Immutable vs Type: reassignment via arrays and performance

Not to be overly pedantic, but that’s not why Ref was added. It was specifically added to act like a view operation on one element, primarily for aiding in C-interop. In fact, it is an abstract type specifically because that allows it to perform its intended function (despite also making it sub-optimal as a annotation for making a field mutable).

From a performance standpoint, it’s usually best if you make the whole object immutable, or the whole object mutable. It’s better (performance and memory) to wrap an entire immutable object in a mutable object (including in a mutable struct or an Array), rather than using Ref (or RefValue or Array or another mutable type) to select multiple specific fields to make mutable. This flattens out the memory hierarchy, meaning the computer needs to do fewer memory fetches to compute the answer.

2 Likes