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,因此具有位移和三元運算符的表達式實際上只是在計算超額分配。
添加回答
舉報