C# Immutability – Do Constantly Changing Immutable Objects Impact Memory/Performance?

cgarbage-collectionimmutabilitymemory usage

I'm writing a program that goes into a loop and keeps changing the state of some models (similar to a game). Naturally, many things are mutable. However, I'm also writing some classes that are immutable because they're inherently treated like values (for example: vectors, matrices, etc.)

However, these values change on every loop (maybe 50-100 times a second). Does this mean that on every change, the program would need to allocate a new chunk of memory? If I'm using managed code, does this mean that the memory usage will build up very quickly? How does this impact determinism, performance, and garbage collection in languages such as C# and Java, especially when many garbage collectors have to pause the entire program in order to clear the memory?

Best Answer

All structs are allocated on stack or is part of memory of containing class. Even if you allocate millions of structures, it is not going to impact memory. On the other hand, passing big struct around by value (not by reference) might impact performance, because it is copied every time.

On the other hand, allocating new class might impact memory consumption, because new class instance = new allocated memory. Also, it might impact performance, because GC needs to keep track of it and dispose it. There are some optimizations like Generational GC, but if you really need performance, it is best to manage the memory yourself.