问题描述
基本上,你有两种方法实现此目的:
Basically you have two ways for doing this:
for (int x = 0; x < UPPER_X; x++)
for (int y = 0; y < UPPER_Y; y++)
{
arr1[x, y] = get_value();
arr2[y, x] = get_value();
}
唯一的区别是什么变量改变在内部循环:第一或第二。我听说,结果从语言不同的语言。
The only difference is what variable to change in the inner loop: first or second. I heard that the results differ from language to language.
什么是正确的顺序为.NET?
What is right order for .NET?
推荐答案
其原因之一就是快于其它有做与处理器的高速缓存的方式,以及数据在内存中排列。
The reason one is faster than the other has to do with the processor's cache, and the way the data is laid out in memory.
有两个正常方式来存储二维数据是一维的地址空间,要么可以存储所有的数据的第一行,然后是第二行,依此类推(又名),也可以通过列做到这一点(又名 列优先的顺序的)。下面是存储位置会是怎样的一个3x3的阵列这两个选项。
There are two normal ways to store the two-dimensional data is in one-dimensional address space, Either you can store all of the data for the first row, then the second row, and so on (aka row major order), or you can do it by columns (aka column major order). Below is what the memory locations would be for a 3x3 array for both of these options.
行:
1 2 3
4 5 6
7 8 9
列:
1 4 7
2 5 8
3 6 9
在访问一个存储单元中,整个高速缓冲存储器线(其可以是8和512字节之间,根据维基百科)被加载到高速缓存中。因此,如果您访问下一个存储器位置,将已经在缓存中。因此,可以更快访问存储器顺序地,而不是在地址空间中跳来跳去。因此,在大的二维数组,可以有选择的行或列,你内心的循环变量之间的显著速度差。
When you access one memory location, an entire cache line (which can be between 8 and 512 bytes, according to Wikipedia) is loaded into the cache. So if you access the next memory location it will already be in the cache. Thus, it can be much faster to access memory sequentially than to jump around in the address space. Thus, with large two-dimensional arrays, there can be a significant speed difference between choosing rows or columns as your inner loop variable.
这篇关于.NET矩形数组:在一个循环中如何访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!