lozzajp
lozzajp

Reputation: 1016

Is there speed differences between iterating an array of bools, ints or longs?

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

Answers (1)

Mio Bambino
Mio Bambino

Reputation: 544

An Array is basically of following structure:

  • an initial memory pointer
  • a value of its length
  • reserved memory from the intial memory 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

Related Questions