Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

How does compiler fetch elements from array of objects in constant time?

Whenever we want to fetch elements based on index from an array, I learned that the compiler just does something like this to fetch the element in constant time:

array_addr + ele_size * (i - first_index) (where the ele_size depends on the type of the elements present in an array, e.g. for array[int] the ele_size will be 4 bytes)

So how does compiler fetch elements from array[object] in constant time, when each object could have a different size (in memory)?

PS: Question is not specific to any language

question from:https://stackoverflow.com/questions/65557392/how-does-compiler-fetch-elements-from-array-of-objects-in-constant-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...