对于内存池这一块接触都有几年的时间了,看了很多代码也不明白,真是差啊,今天把这本书的代码抄了一遍,代码在Linux下编译有些问题
1.全局函数
关于static_cast在gcc 4.1.2上使用有误
- #include <iostream>
- class Rational
- {
- public:
- Rational (int a = 0, int b = 1) : n(a),d(b) {}
- private:
- int n;
- int d;
- };
- int main()
- {
- Rational *array[1000];
- for (int j = 0; j < 500; j++)
- {
- for (int i = 0; i < 1000; i++)
- {
- array[i] = new Rational(i);
- }
- for (int i = 0; i < 1000; i++)
- {
- delete array[i];
- }
- }
- return 0;
- }
2 .专用Rational 内存管理器
1.依然是static_cast的使用
- #include <iostream>
- class NextOnFreeList
- {
- public:
- NextOnFreeList *next;
- };
- class Rational
- {
- public:
- Rational (int a = 0, int b = 1) : n(a),d(b) {}
- inline void *operator new(size_t size);
- inline void operator delete(void *doomed,size_t size);
- static void newMemPool() { expandTheFreeList();}
- static void deleteMemPool();
- private:
- static NextOnFreeList *freeList;
- static void expandTheFreeList();
- enum { EXPANSION_SIZE = 32};
- int n; //numerator
- int d; //denominator
- };
- inline size_t mymax(size_t a,size_t b) { return a > b ? a: b;}
- inline
- void* Rational::operator new(size_t size)
- {
- if (0 == freeList)
- {
- expandTheFreeList();
- }
- NextOnFreeList *head = freeList;
- freeList = head->next;
- return head;
- }
- inline
- void Rational::operator delete(void* doomed, size_t size)
- {
- NextOnFreeList *head = static_cast<NextOnFreeList *> (doomed);
- head->next = freeList;
- freeList = head;
- }
- void Rational::expandTheFreeList()
- {
- size_t size = mymax(sizeof(Rational),sizeof(NextOnFreeList *));
- NextOnFreeList *runner = static_cast<NextOnFreeList *> (static_cast<void *>(new char[size]));
- freeList = runner;
- for (int i = 0; i < EXPANSION_SIZE; i++)
- {
- runner->next = static_cast<NextOnFreeList *> (static_cast<void *>(new char[size]));
- runner = runner->next;
- }
- runner->next = NULL;
- }
- NextOnFreeList* Rational::freeList = NULL;
- int main()
- {
- Rational *array[1000];
- for (int j = 0; j < 500; j++)
- {
- for (int i = 0; i < 1000; i++)
- {
- array[i] = new Rational(i);
- }
- for (int i = 0; i < 1000; i++)
- {
- delete array[i];
- }
- }
- return 0;
- }
我所使用的系统是虚拟机,经过测试第二个是第一个效率的2倍
使用Tcmalloc的效率提升多少没有实验
阅读(831) | 评论(0) | 转发(1) |