简体   繁体   中英

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. I'm trying to optimize the array creation.

Thanks!

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. 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

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. In fact, one potential improvement does leap out: at the moment, you're accessing the map arrays like this:

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; it all depends on the architecture of the machine.

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