3 回答

TA貢獻(xiàn)2051條經(jīng)驗(yàn) 獲得超10個(gè)贊
在回答這樣的問題時(shí),一種方法是僅“欺騙”并查看流行的庫所做的事情,前提是假定廣泛使用的庫至少?zèng)]有做任何可怕的事情。
因此,只需快速檢查一下,Ruby(1.9.1-p129)在追加到數(shù)組時(shí)似乎使用1.5x,而Python(2.6.2)使用1.125x加一個(gè)常量(在中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以上是數(shù)組中元素的數(shù)量。請(qǐng)注意,它newsize已添加到new_allocated,因此具有位移和三元運(yùn)算符的表達(dá)式實(shí)際上只是在計(jì)算超額分配。
添加回答
舉報(bào)