RyanLeeLY/FastKV

hi

Closed this issue · 3 comments

感觉内存分配可以 new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6); 这样处理。翻倍的话 可能不是一个很好的处理方式。

有点不明白,这个newsize是什么?能讲一下这个思路吗?

我查了一下,python的list分配规则就是这个new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);
newsize就是你预计需要的size。

/* This over-allocates proportional to the list size, making room
* for additional growth.  The over-allocation is mild, but is
* enough to give linear-time amortized behavior over a long
* sequence of appends() in the presence of a poorly-performing
* system realloc().
* The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
*/
new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);

/* check for integer overflow */
if (new_allocated > PY_SIZE_MAX - newsize) {
    PyErr_NoMemory();
    return -1;
} else {
    new_allocated += newsize;
}

see reference here

这个可能还是看具体的使用场景吧。在FastKV中的realloc时间开销要比python中的list的realloc大得多,主要时间消耗会在数据排重,缓慢的增长模型是一种以时间换空间的做法。
比如在有的APP启动的时候在短时间内会有大量append操作,如果内存分配增长过慢,数据排重和mmap重分配次数会比较多。在append操作比较少且单次数据量不大的情况下甚至可以按页分配,使之线性增长。总之,这是一种时间和空间的权衡,可以看具体使用场景。 @hzqjyyx @xiaoheiai4719