3 回答
TA贡献2051条经验 获得超10个赞
在回答这样的问题时,一种方法是仅“欺骗”并查看流行的库所做的事情,前提是假定广泛使用的库至少没有做任何可怕的事情。
因此,只需快速检查一下,Ruby(1.9.1-p129)在追加到数组时似乎使用1.5x,而Python(2.6.2)使用1.125x加一个常量(在中Objects/listobject.c):
/* 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;
}
newsize以上是数组中元素的数量。请注意,它newsize已添加到new_allocated,因此具有位移和三元运算符的表达式实际上只是在计算超额分配。
添加回答
举报