FastAlloc.h
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019 #ifndef ADCHPP_FASTALLOC_H
00020 #define ADCHPP_FASTALLOC_H
00021
00022 #include "Mutex.h"
00023
00024 namespace adchpp {
00025
00026 #ifdef NDEBUG
00027 struct FastAllocBase {
00028 ADCHPP_DLL static FastMutex mtx;
00029 };
00030
00035 template<class T>
00036 struct FastAlloc : public FastAllocBase {
00037
00038 static void* operator new(size_t s) {
00039 if(s != sizeof(T))
00040 return ::operator new(s);
00041 return allocate();
00042 }
00043
00044
00045 static void* operator new(size_t, void* m) {
00046 return m;
00047 }
00048
00049 static void operator delete(void*, void*) {
00050
00051 }
00052
00053 static void operator delete(void* m, size_t s) {
00054 if (s != sizeof(T)) {
00055 ::operator delete(m);
00056 } else if(m != NULL) {
00057 deallocate((uint8_t*)m);
00058 }
00059 }
00060 private:
00061
00062 static void* allocate() {
00063 FastMutex::Lock l(mtx);
00064 if(freeList == NULL) {
00065 grow();
00066 }
00067 void* tmp = freeList;
00068 freeList = *((void**)freeList);
00069 return tmp;
00070 }
00071
00072 static void deallocate(void* p) {
00073 FastMutex::Lock l(mtx);
00074 *(void**)p = freeList;
00075 freeList = p;
00076 }
00077
00078 static void* freeList;
00079
00080 static void grow() {
00081 dcassert(sizeof(T) >= sizeof(void*));
00082
00083 size_t items = ((128*1024 + sizeof(T) - 1)/sizeof(T));
00084 freeList = new uint8_t[sizeof(T)*items];
00085 uint8_t* tmp = (uint8_t*)freeList;
00086 for(size_t i = 0; i < items - 1; i++) {
00087 *(void**)tmp = tmp + sizeof(T);
00088 tmp += sizeof(T);
00089 }
00090 *(void**)tmp = NULL;
00091 }
00092 };
00093 template<class T> void* FastAlloc<T>::freeList = 0;
00094 #else
00095 template<class T> struct FastAlloc { };
00096 #endif
00097
00098 }
00099
00100 #endif // FASTALLOC_H