雖然我不認爲這是一個好主意,一個解決辦法是有各種日誌的預分配桶大小,愚蠢的僞代碼:
class Allocator {
void* malloc(size_t size) {
int bucket = log2(size + sizeof(int));
int* pointer = reinterpret_cast<int*>(m_buckets[bucket].back());
m_buckets[bucket].pop_back();
*pointer = bucket; //Store which bucket this was allocated from
return pointer + 1; //Dont overwrite header
}
void free(void* pointer) {
int* temp = reinterpret_cast<int*>(pointer) - 1;
m_buckets[*temp].push_back(temp);
}
vector< vector<void*> > m_buckets;
};
(當然,你也用一個簡單的數組+計數器替換std::vector
)。
編輯:爲了使這個強大的(即處理桶是空的情況),你將不得不添加某種形式的分支。
EDIT2:這裏有一個小網點log2
功能:
//returns the smallest x such that value <= (1 << x)
int
log2(int value) {
union Foo {
int x;
float y;
} foo;
foo.y = value - 1;
return ((foo.x & (0xFF << 23)) >> 23) - 126; //Extract exponent (base 2) of floating point number
}
這爲分配< 33554432字節正確的結果。如果你需要更大的分配,你將不得不切換到雙打。
這裏是一個link浮點數如何表示在內存中。
你是什麼意思的「分支」? – 2010-03-22 10:23:08
@Neil,我想,這是分裂控制流的東西(例如'if'運算符)。 – 2010-03-22 10:30:48
如果分支意味着「如果」,那麼答案是否定的。 @OP:請你澄清一下,如果這確實是你的意思? – 2010-03-22 11:10:52