我很好奇使用高维数组与一维数组的效率。在定义和迭代这样的数组时,您是否会丢失任何东西:
array[i][j][k];
或定义和迭代这样的数组:
array[k + j*jmax + i*imax];
我的倾向是不会有区别,但我仍在学习高效编程(我以前从未关心过这种事情)。
谢谢!
我很好奇使用高维数组与一维数组的效率。在定义和迭代这样的数组时,您是否会丢失任何东西:
array[i][j][k];
或定义和迭代这样的数组:
array[k + j*jmax + i*imax];
我的倾向是不会有区别,但我仍在学习高效编程(我以前从未关心过这种事情)。
谢谢!
The former way and the latter way to access arrays are identical once you compile it. Keep in mind that accessing memory locations that are close to one another does make a difference in performance, as they're going to be cached differently. Thus, if you're storing a high-dimensional matrix, ensure that you store rows one after the other if you're going to be accessing them that way.
In general, CPU caches optimize for temporal and spacial ordering. That is, if you access memory address X, the odds of you accessing X+1 are higher. It's much more efficient to operate on values within the same cache line.
Check out this article on CPU caches for more information on how different storage policies affect performance: http://en.wikipedia.org/wiki/CPU_cache
If you can rewrite the indexing, so can the compiler. I wouldn't worry about that.
Trust your compiler(tm)!
唯一确定的方法是对两种方式进行基准测试(当然,在编译器中使用优化标志)。认为在第二种方法中你肯定会失去的是阅读的清晰度。
Do yourself a favor and care about such things after profiling the code. It is very unlikely that something like that will affect the performance of the application as a whole. Using the correct algorithms is much more important
And even if it does matter, it is most certainly only a single inner loop that needs attention.
它可能取决于实现,但我会说它或多或少相当于你的一维数组代码。