内存池版本2单线程固定大小对象的内存池

#include "stdafx.h"
#include
<windows.h>
#include
<MMSystem.h>
#include
<iostream>
using namespace std;

#pragma comment(lib, "winmm.lib")

template
<typename T>
class MemoryPool
{
public:
MemoryPool(size_t size
= EXPAND_SIZE);
~MemoryPool();
inline
void* alloc(size_t size); //分配一个T类型的对象
inline void free(void* doomed); //释放一个T类型的指针

//private:
enum {EXPAND_SIZE = 3};
MemoryPool
<T>* pNext;

void ExpandFreeList(size_t num = EXPAND_SIZE);
};

template
<typename T>
MemoryPool
<T>::MemoryPool(size_t size = EXPAND_SIZE)
{
ExpandFreeList(size);
}

template
<typename T>
MemoryPool
<T>::~MemoryPool()
{
if (pNext != 0)
{
MemoryPool
<T>* ptr = pNext;
for (; ptr != NULL; ptr = pNext)
{
pNext
= pNext->pNext;
delete []ptr;
}
}
}


template
<typename T>
inline
void* MemoryPool<T>::alloc(size_t size)
{
if (pNext == 0)
{
ExpandFreeList(EXPAND_SIZE);
}

MemoryPool
<T>* ptr = pNext;
pNext
= pNext->pNext;
return ptr;
}

template
<typename T>
inline
void MemoryPool<T>::free(void* doomed)
{
MemoryPool
<T>* ptr = static_cast<MemoryPool<T>* >(doomed);
ptr
->pNext = pNext;
pNext
= ptr;
}


template
<typename T>
void MemoryPool<T>::ExpandFreeList(size_t num /* = EXPAND_SIZE */)
{
size_t size
= sizeof(T) > sizeof(MemoryPool<T>*) ? sizeof(T) : sizeof(MemoryPool<T>*);
MemoryPool
<T>* ptr = (MemoryPool<T>*)(new char[size]);
pNext
= ptr;
for (int i=0; i<num; ++i)
{
ptr
->pNext = (MemoryPool<T>*)(new char[size]);
ptr
= ptr->pNext;
}

ptr
->pNext = 0;
}

class Foo2
{
public:
Foo2(
int a = 0, int b = 0):m(a), n(b) {}
void* operator new (size_t size) {return pool->alloc(size);}
void operator delete (void* doomed) {return pool->free(doomed);}

static void NewMemoryPool() { pool = new MemoryPool<Foo2>;}
static void FreeMemoryPool()
{
if (pool)
{
delete pool;
}
}

private:
int m;
int n;

static MemoryPool<Foo2>* pool;
};

MemoryPool
<Foo2>* Foo2::pool = 0;


class Foo
{
public:
Foo(
int a = 0, int b = 0):m(a), n(b) {}

private:
int m;
int n;
};


int main()
{
DWORD time1, time2, deltaTime;
time1
= timeGetTime();
for (int i=0; i<500; ++i)
{
Foo
* ptrArray[1000];
for (int j=0; j<1000; ++j)
{
ptrArray[j]
= new Foo;
}

for (int j=0; j<1000; ++j)
{
delete ptrArray[j];
}
}

time2
= timeGetTime();
deltaTime
= time2- time1;
cout
<<deltaTime<<endl;

Foo2::NewMemoryPool();
time1
= timeGetTime();
for (int i=0; i<500; ++i)
{
Foo2
* ptrArray[1000];
for (int j=0; j<1000; ++j)
{
ptrArray[j]
= new Foo2;
}

for (int j=0; j<1000; ++j)
{
delete ptrArray[j];
}
}

time2
= timeGetTime();
deltaTime
= time2- time1;
Foo2::FreeMemoryPool();
cout
<<deltaTime<<endl;

return 0;
}

  

原文地址:https://www.cnblogs.com/kex1n/p/2138495.html