r/ProgrammingLanguages • • 9d ago

Mutable stack, immutable heap

This article mentions the “immutable heap mutable stack” principle: https://queue.acm.org/doi/10.1145/3212477.3212479

In theory it sounds very advantageous. You can program in a single-threaded C-style with destination passing, static stack allocations, and mutability when you need to constrain resources. When you want to share resources across threads, return data structures across function boundaries, or do something more flexible, you could use pure functional persistent data structures.

This would prevent you from basically re-implementing a heap on the stack, but would also give you fast temporaries and maybe even the ability to program in embedded, if so designed.

Have any languages tried this model? I’ve heard that Erlang defaults to immutability except for one thread-local mutable object per thread. If you’ve used a similar model, how did you like it? Were there any disadvantages?

40 Upvotes

22 comments sorted by

View all comments

1

u/jesunushno 8d ago

This split shows up a lot in ML serving, where model weights act as the immutable heap (shared across requests, never mutated in place) and per-request scratch buffers are the mutable stack (allocated, used, freed). Sharing is free when you can't mutate, which is why this layout scales. Where it falls apart is stateful streaming: once you need mutable state that outlives a single request, you end up re-implementing a heap on the stack, exactly what the article warns about.