Why mutable structs are allocated on the heap?

It says heap allocation is generally (read: usually) required for stable memory address (which represent object identity for mutable objects). So the logic is that, in order to support mutable, the only object identity you can have is the address (or if you want to take address out of the picture, you at least need a way to distinguish object constructed differently but have the same value), which means that you’ll usually need to heap allocate it.

The doc could be better, but it is also a bad idea to go deeply into optimization when introducing a concept. It’s of course very hard in this context to not talk about optimizations at all since some of the optimizations are “guaranteed” for type stable code but this part of the doc should (edit: not) go into all the details about what optimization can the compiler do.

After all, for non-escaping allocation, the compiler can literally do anything about the object including eliminate it (i.e. not allocating it at all). It’s also not wrong by saying that they are usually allocated on the heap since they are either allocated on the heap or not allocated at all (i.e. when they are allocated, it’s almost always on the heap).

It is very common for scripting language to only have one object passing semantics (by reference) and this is basically another way of saying assignment is a no-op or there’s no concept of stack/local variable in C in the language. (Note that this is basically the same as saying all objects are conceptually allocated on the heap.)
On top of this, immutable object seems to be a pretty standard concept and in this case is really efficient to allow arbitrary allocation for immutable objects so it makes sense to have it though I have no idea how it was originally decided…

(edit: pressed Ctrl-Enter by accident)

Why storing mutables as refs is a good thing?

It’s not a good thing. With the current computer architecture where values are stored in memory and pointers to those memory location are called pointer/reference, this is the only (or at least the simplest) thing you can do to keep track of object identity.

3 Likes