Currently, I have all my objects managing their own memory, allocating with new in their constructors typically, and using delete in their destructors. This works for now, but the number of classes I have that use arbitrary amounts of memory is growing. The fact that new is essentially a “request” also bothers me, since these objects have no code within them to handle being told “no”, and I don’t want to rely on Exception Handling if I do not need to.
-
Is it beneficial in terms of performance to completely
shield all calls that allocate memory, to a single class that handles
every memory allocation on the heap, probably allocating large chunks
at a time and using placement new to deal out references? -
Is the use of memory allocation in smaller classes a big enough concern to even bother with this?
-
Can I still use STL containers and force them to use the heap I
provide?
Thank you in advance!
STL containers accept custom allocators:
http://en.wikipedia.org/wiki/Allocator_(C%2B%2B)#Custom_allocators
Here is a thread with links to samples:
Compelling examples of custom C++ allocators?
You can only find out by writing your application, coming up with a set of reproducible test scenarios, and running your code in a profiler. If you find the memory allocation to be a significant portion of the running time, then you might benefit from a better allocation strategy.
If you can break up your program to a feature level, and can come up with realistic scenarios for each case, you don’t have to have your whole program working to do this. But remember that time spent optimizing is time that could be spent testing or coding new features 🙂 Do what is necessary and no more…
Depending on your program, how sensitive you are to big allocation hitches, how often you allocate in loops, etc, it is possible. Profile 🙂
While developing your app, you can still be sensitive to allocations – create automatic storage (stack local) variables when you can, and allocate dynamically only when you must.