Reputation: 1016
I am mainly interested in C# but general answers are welcome too.
Would it take longer to iterate over an array of longs compared to ints? I imagine that the larger value types take up more memory so a contiguous array is obviously longer. But is the hop from Array[0] to Array[1] any different if that gap is 8, 16 or 32 bytes etc?
If it is, would a large struct type (because its by value) take even longer?
Or is traversing an array kinda just memory pointer to memory pointer and the gaps/location of the next item not really relevant?
Upvotes: 0
Views: 84
Reputation: 544
An Array is basically of following structure:
pointer + sizeof(type) * length
With these three informations it's trivial to point to the exact location of any value:
memory pointer + sizeof(type) * element
where 0 <= element < length
When accessing a distinct value in an array the compiler will translate it to perform such a calculation and load the value at the given position (here: in primitives). There are no gaps inbetween, because the very definition of it makes the O(1)
possible (and neccessary).
Upvotes: 2