So how does compiler fetch elements from array[object]
in constant time (as the size of the objects could vary)?
Well, the expression that is being evaluated is:
array_addr + ele_size * (i - first_index)
where ele_size
is a constant that depends on the (compile time) type of the array, and first_index
is also typically a constant; e.g. zero for C, C++, Java, etcetera.
That is one subtraction (when first_index
is not the constant zero), one multiplication, one addition, and possibly a memory fetch or two.
Either way, the number of machine instructions required to perform the calculation is a constant. Hence (modulo quibbling about variable memory fetch times, pipeline effects, etc) the time taken for one such computation will be a constant ... irrespective of the values of the notional expression parameters.
Quibble: The compiler doesn't fetch the elements. It generates code that will fetch elements ... when the code is executed.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…