简体   繁体   中英

Speed of iterating through 1-dimensional vs 2-dimensional arrays

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM