Allocation Cost
Allocation Cost
Allocation Cost
Prerequisites
1. Why Allocation Matters
Memory allocation is not free.
π Costs include:
- Heap allocation (
new,malloc) - System calls / allocator overhead
- Cache misses
- Memory fragmentation
Frequent allocation/deallocation can become a major performance bottleneck
2. Vector Allocation
β Growth behavior
1
2
std::vector<int> v;
v.push_back(1);
When capacity is exceeded:
- New memory allocated
- Old data copied/moved
- Old memory freed
β Problem Example
1
2
3
4
5
for (int i = 0; i < N; i++)
{
std::vector<int> v;
v.push_back(i);
}
Every iteration:
- Allocation
- Possible reallocation
- Deallocation
β Huge overhead in tight loops
β Use reserve
1
2
3
4
5
std::vector<int> v;
v.reserve(N);
for (int i = 0; i < N; i++)
v.push_back(i);
Allocates once β no reallocation
β Reuse memory
1
2
3
4
5
6
7
8
std::vector<int> v;
v.reserve(N);
for (int i = 0; i < N; i++)
{
v.clear(); // keeps capacity
v.push_back(i);
}
- No allocation inside loop
- Only logical reset
| Function | Effect |
|---|---|
clear() | Removes elements, keeps memory |
shrink_to_fit() | Requests memory release |
- Use
clear()for reuse - Avoid
shrink_to_fit()in hot paths
3. Object Pool
Reuse objects instead of repeatedly allocating/deallocating them
β Basic Idea
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class ObjectPool
{
std::vector<MyObject> pool;
int index = 0;
public:
MyObject& acquire()
{
return pool[index++];
}
void reset()
{
index = 0;
}
};
β Usage
1
2
3
4
5
6
7
8
ObjectPool pool;
for (...) {
auto& obj = pool.acquire();
// use obj
}
pool.reset(); // reuse all objects
No allocation during runtime loop
β DO
- Reserve memory upfront
- Reuse containers (
clear()instead of recreate) - Use object pool for repeated allocation
- Minimize heap operations in loops
β DONβT
- Allocate inside tight loops
- Frequently call
new/delete - Use
shrink_to_fit()repeatedly
This post is licensed under CC BY 4.0 by the author.