简体   繁体   English

对于遍历2D数组的循环来说,这快于2还是快于相同的速度?

[英]Is this faster than 2 for loops for iterating through a 2D array, or is it the same speed?

for (int x = 0; x < height; x++) {
        map[x][y] = new Plot(x, y, "map");
        if (x == 199 && y < 199) {
            x = 0;
            y++;
        }
    }

I have this code here that I set up to create a 2D array of 200x200 objects for a map, and I would like to know if it is the same speed or if it indeed runs faster. 我在这里有这段代码,我设置它来为地图创建一个200x200对象的2D数组,我想知道它是相同的速度还是运行的更快。 I'm trying to optimize the array creation. 我正在尝试优化数组的创建。

Thanks! 谢谢!

EDIT : assuming Y starts at 0, and height is 200 always EDIT 2 : Thank you to everybody who answered :D Yes I could've created something to test it, but eh 编辑:假设Y从0开始,高度始终为200 编辑2:谢谢所有回答的人:D是,我可以创建一些东西对其进行测试,但是

Just think about it, if you have ie 200*200 array and you want to put some new instance into each of it, you have to do it in every single "cell" = 40000 cells. 试想一下,如果您有200 * 200数组,并且想要在每个数组中放入一些新实例,则必须在每个“单元” = 40000个单元中进行操作。 You cant be better than that no matter the optimization. 无论如何优化,都不能比这更好。

Even if you dont have for-cycle and do it with 即使你没有周期,并与

x[0][0] = ...
x[0][1] = ...

You still have to write 40000 commands 您仍然必须编写40000条命令

The generated code will not be faster - the instructions generated will be almost identical; 生成的代码不会更快-生成的指令几乎相同; in fact, when compiler optimisations are turned on, the compiler might struggle to optimise either loop effectively because it can't recognise them as simple loops. 实际上,当打开编译器优化时,编译器可能无法有效地优化任一循环,因为它无法将它们识别为简单循环。

The vast majority of the execution time will be spent allocating the new memory, and writing pointers to the map arrays. 执行时间的绝大部分将用于分配新的内存,以及将指针写入map数组。 In fact, one potential improvement does leap out: at the moment, you're accessing the map arrays like this: 实际上,确实有一项潜在的改进可以实现:目前,您正在以如下方式访问map数组:

map[0][0]
map[1][0]
map[2][0]
...
map[0][1]
map[1][1]
map[2][1]
...
map[0][2]

and so on. 等等。

This is undesirable, because the addresses are far apart in memory. 这是不希望的,因为地址在内存中相距很远。 It is always better to access memory in such a way that addresses that are close to each other are accessed near to each other in time, because this is much friendlier to the cache. 始终最好以这样的方式访问内存:及时访问彼此接近的地址,因为这对缓存更友好。

So if you were to swap the order of iteration round (eg [0][0], [0][1], [0][2], ... [1][0], [1][1], [1][2]... ) then you might find your code runs quicker - or you might not; 因此,如果您要交换迭代周期的顺序(例如[0][0], [0][1], [0][2], ... [1][0], [1][1], [1][2]... ),那么您可能会发现代码运行得更快-或可能不会; it all depends on the architecture of the machine. 这一切都取决于机器的体系结构。

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

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