简体   繁体   English

一维数组与二维数组的迭代速度

[英]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? ). 我正在阅读一篇关于二维数组在水平方向上比在垂直方向上迭代快的方法,这是因为数据的存储方式(请参阅: 循环遍历2d数组的最快方法? )。 That made sense when I read the answer but it got me wondering what the difference was between 2 and 1 dimensional arrays. 当我阅读答案时,这很有意义,但让我想知道2维和1维数组之间的区别是什么。 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. 在Java上,还有更多因素和更多的数组开销。 As arrays are objects, int[][] is an array of array objects of ints . 由于数组是对象,因此int[][]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. 但是,这种微优化不一定是时间的最佳利用,因为可能会有更好的改进地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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