| 1 |
#if !defined(_CLEAROPTIMIZEHEAP_H_) |
| 2 |
#define _CLEAROPTIMIZEHEAP_H_ |
| 3 |
|
| 4 |
/** |
| 5 |
* @class ClearOptimizeHeap |
| 6 |
* @brief A heap layer that is optimized for region-like allocation patterns. |
| 7 |
* @param Heap1 This heap provides memory for freshly allocated objects. |
| 8 |
* @param Heap2 This heap provides memory for recycled objects. |
| 9 |
*/ |
| 10 |
|
| 11 |
template <class Heap1, class Heap2> |
| 12 |
class ClearOptimizeHeap: public Heap1, Heap2 { |
| 13 |
public: |
| 14 |
|
| 15 |
inline ClearOptimizeHeap (void) |
| 16 |
: nothingOnHeap (true) |
| 17 |
{ |
| 18 |
} |
| 19 |
|
| 20 |
inline void * malloc (const size_t sz) { |
| 21 |
if (nothingOnHeap) { |
| 22 |
return Heap1::malloc (sz); |
| 23 |
} else { |
| 24 |
void * ptr = Heap2::malloc (sz); |
| 25 |
if (ptr == NULL) { |
| 26 |
// Right now we assume that this means that the heap is in fact |
| 27 |
// exhausted. This is not necessarily true, but it's a reasonable |
| 28 |
// approximation, and is a lot cheaper than tracking the complete |
| 29 |
// state of the parent heap. |
| 30 |
nothingOnHeap = true; |
| 31 |
ptr = Heap1::malloc (sz); |
| 32 |
} |
| 33 |
return ptr; |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
inline void free (void * ptr) { |
| 38 |
#if 1 |
| 39 |
nothingOnHeap = false; |
| 40 |
#else |
| 41 |
if (nothingOnHeap) { |
| 42 |
nothingOnHeap = false; |
| 43 |
} |
| 44 |
#endif |
| 45 |
Heap2::free (ptr); |
| 46 |
} |
| 47 |
|
| 48 |
inline int remove (void * ptr) { |
| 49 |
return Heap2::remove (ptr); // heap2.remove (ptr); |
| 50 |
} |
| 51 |
|
| 52 |
inline void clear (void) { |
| 53 |
Heap1::clear(); |
| 54 |
if (!nothingOnHeap) { |
| 55 |
Heap2::clear(); ///heap2.clear(); |
| 56 |
} |
| 57 |
nothingOnHeap = true; |
| 58 |
} |
| 59 |
|
| 60 |
inline size_t getSize (const void * ptr) { |
| 61 |
return Heap2::getSize (ptr); |
| 62 |
} |
| 63 |
|
| 64 |
private: |
| 65 |
|
| 66 |
/// True iff there is nothing on heap 2. |
| 67 |
#ifdef WIN32 |
| 68 |
BOOL nothingOnHeap; |
| 69 |
#else |
| 70 |
bool nothingOnHeap; |
| 71 |
#endif |
| 72 |
// Heap2 heap2; |
| 73 |
}; |
| 74 |
|
| 75 |
#endif |