c 快取池實現

2021-09-26 01:31:22 字數 1764 閱讀 5962

一、問題與實現

眾所周知,在c++中頻繁的new與delete其實是很消耗時間的,在要求高效能的地方,一般需要使用快取池對記憶體進行使用與**。快取池的意思的就是事先分配好一定的空間,在使用時提供給使用者,使用者在用完後歸還。只在開始和結束時進行new與delete,優勢就是可以大大提高效率,劣勢就是pop與push必須成對使用,不然就會造成記憶體洩漏,且非常不容易追蹤。

**實現如下:

memorypool.h

#ifndef memory_pool_h

#define memory_pool_h

struct node

;templateclass memory_pool

else

}_cur_count = len;

_parcel_count = len;

}t* pop()

else

--_cur_count;

return (t*)(n->_buff + sizeof(void*));

}void push(t *t)

else

++_cur_count;

}~memory_pool()

}private:

node *_head;

node *_tail;

int _cur_count; // 當前池中存在的數量

int _parcel_count; // 當前new出來的數量

};#endif // memory_pool_h

memorypooltest.h

#ifndef memory_pool_test_h

#define memory_pool_test_h

#include "memorypool.h"

#include #include struct test_data

~test_data()

void do_some_thing()

int _i = 0;

};class memory_pool_test

for (int i = 0; i < vec_data.size(); i++)

delete _pool_test_data;

}memory_pool*_pool_test_data;

};#endif

main.cpp

#include "memorypooltest.h"

int main()

執行結果:

二、原理

我們建立了乙個 struct node 的鍊錶結構,把其中的_buff提供給使用者去使用,同時_buff中還包含了自己的節點的指標,所以當使用者push回使用物件指標時,我們能夠重新找回node節點,具體記憶體結構如下圖:

在pop時將buff的值偏移sizoef(void*),同時呼叫建構函式,將物件指標給使用者使用。

當使用者push回t物件指標時,只要把指標位址減去sizoef(void *),就能重新得到node結構的指標,有了node指標可以重建鍊錶,方便管理記憶體,從而不造成記憶體洩漏。

Message快取池的實現原理

原理就是採用了在乙個message的類變數,維護了乙個message例項的鍊錶 以下是部分源 和注釋 private static message spool 類變數,表示message池,指向鍊錶的表頭 private static int spoolsize 0 鍊錶的長度 private st...

快取常量池

亞信面試題 先說結論 integer a 127 integer b 127 integer c 128 integer d 128 a b true c d false integer a new integer 127 integer b new integer 127 integer c ne...

LRU在MySQL快取池的實現

mysql的innodb引擎設定有索引及資料快取池,其中用到的lru演算法來維持快取的命中率 這裡用到了順序表list來作為緩衝池,每個資料節點稱為block 該演算法採用 中點插入法 當插入乙個新block時,移除表尾最近最少使用的block,在中點插入新block。這個中點將鍊錶分為兩部分 1....