Created
June 18, 2015 02:00
-
-
Save bricerebsamen/90b4f9eddbbac6401120 to your computer and use it in GitHub Desktop.
comparison of memory pool implementations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef __SEGMENTATION__MEMORY_POOL__H__ | |
#define __SEGMENTATION__MEMORY_POOL__H__ | |
#define NO_POOL 0 | |
#define BOOST_POOL 1 | |
#define CUSTOM_POOL 2 | |
#define USE_POOL NO_POOL | |
#if USE_POOL == BOOST_POOL | |
#include <boost/pool/object_pool.hpp> | |
#define MemoryPool boost::object_pool | |
#else //USE_POOL == CUSTOM_POOL | |
#include <vector> | |
#include <set> | |
#include <boost/foreach.hpp> | |
template <typename T> | |
class MemoryPool | |
{ | |
public: | |
T * construct(); | |
void destroy(T *); | |
#if USE_POOL == CUSTOM_POOL | |
~MemoryPool(); | |
private: | |
typename std::vector<T *> ins_; | |
typename std::set<T *> outs_; | |
#endif | |
}; | |
#if USE_POOL == CUSTOM_POOL | |
template <typename T> | |
MemoryPool<T>::~MemoryPool() | |
{ | |
BOOST_FOREACH(T * p, ins_) { | |
delete p; | |
} | |
BOOST_FOREACH(T * p, outs_) { | |
delete p; | |
} | |
} | |
template <typename T> | |
T * MemoryPool<T>::construct() | |
{ | |
T * p = NULL; | |
if( ins_.empty() ) { | |
p = new T(); | |
} | |
else { | |
p = ins_.back(); | |
ins_.pop_back(); | |
} | |
outs_.insert(p); | |
return p; | |
} | |
template <typename T> | |
void MemoryPool<T>::destroy(T * p) | |
{ | |
ins_.push_back(p); | |
outs_.erase(p); | |
} | |
#elif USE_POOL == NO_POOL | |
template <typename T> | |
T * MemoryPool<T>::construct() | |
{ | |
return new T(); | |
} | |
template <typename T> | |
void MemoryPool<T>::destroy(T * p) | |
{ | |
delete p; | |
} | |
#else | |
#error bad pool implementation | |
#endif | |
#endif //USE_POOL == CUSTOM_POOL | |
#endif // __SEGMENTATION__MEMORY_POOL__H__ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment