Reputation: 2139
I was reading a post on how iterating through a 2-dimesional array horizontally is faster than vertically because of the way the data is stored(See:Fastest way to loop through a 2d array?). That made sense when I read the answer but it got me wondering what the difference was between 2 and 1 dimensional arrays. Is there any speed difference in iterating 1-dimension vs 2-dimension arrays with the same number of cells?
Upvotes: 0
Views: 557
Reputation: 41271
On Java, there are many more factors and more overhead with arrays. As arrays are objects, int[][]
is an array of array objects of ints
. This may make horizontal iteration faster than vertical if hotspot optimizes or caches the array access.
For one vs two dimensional, one-dimensional would be faster as it's an array lookup and a primitive vs an array lookup, a dereference of a reference of an array object, and then a lookup in that array.
However, such microoptimization is not necessarily the best use of your time, as there are likely better places for improvements.
Upvotes: 3