This is a general programming question.
I have seen on a lot of posts that iterating through a 2d array via a double for loop is “horrible” “ugly” etc… Why is this?
Are arrays not an efficient data structure compared to dictionaries and such, and also is not a double for loop more efficient than a foreach or other alternative?
Also if your using a 2d array you are often dealing with a 2d coordinate system. The x and y positions are already “built in” to the data structure as the indexes of the arrays (so you dont need to add ,say, a tuple as a dictionary key) and by changing the for loop paramaters you can very cheaply iterate through different parts of your grid while totally ignoring the parts you dont want to iterate through. For example to avoid the “outer” rows and columns you could do..
for (int x = 1; x < Grid.GetLength(0)-1; x++)
{
for (int y = 1; y < Grid.GetLength(1)-1; y++)
{
Grid[x,y].DoSomething();
}
}
With a foreach you’d iterate through everything in the collection and then have something to check whether it is in the coordinate range you want.
Nothing wrong with 2 loops for iterating a 2D array, as long as this is what you really need to do.
One thing to note is performance – in general, the looping should follow the layout of the array in memory. E.g., if the 2D array is stored as a 1D memory buffer where row
nis stored after rown-1(this is the common implementation in general purpose languages), the external loop should go through the rows and internal one through the columns. This way cache misses are minimized.In general, effectiveness of array access compared to other methods completely depends on particular language implementation. Usually, the array would be the most primitive data structure, resulting in the fastest access. BTW, dictionary is a generalization of array concept.