Comment by andsoitis
2 months ago
> Allocate all necessary memory during startup and avoid dynamic memory allocation after initialization.
Why?
2 months ago
> Allocate all necessary memory during startup and avoid dynamic memory allocation after initialization.
Why?
I think they are hinting at the idea that a long running process on a dedicated server should allocate all necessary memory during initialization. That way you never accidentally run out of memory during high loads, a time when you really don't want your service to go down.
You would need so much more physical memory with this approach. For example, you may want to allocate a lot of memory for the browser, but then close the tab. 2 seconds later you want to use it for a compiler. And then you switch to a code editor.
Two reasons.
1. Dynamic memory allocation is error prone. Mixing it in with your control flow makes that hard to manage.
Many of the strategies for keeping track of dynamic memory add significantly to the complexity of the program... You need to consider object ownership, maybe introduce reference counting, even garbage collection, or "borrow checkers".
If you can avoid all of that by making good architectural choices up front then your code will be much simpler and robust.
2. Dynamic allocation is slow, especially in a multithreaded environment. It's doubly slow if you layer garbage checking or whatever on top of it.
Prefer fewer trips to the allocator, preferably none in your code's hot path.
You can run out of memory and trigger a crash.