cperformancearrays

Representing a 2D array as a 1D array


Possible Duplicates:
Implementing a matrix, which is more efficient - using an Array of Arrays (2D) or a 1D array?
Performance of 2-dimensional array vs 1-dimensional array

I was looking at one of my buddy's molecular dynamics code bases the other day and he had represented some 2D data as a 1D array. So rather than having to use two indexes he only has to keep track of one but a little math is done to figure out what position it would be in if it were 2D. So in the case of this 2D array:

two_D = [[0, 1, 2],
         [3, 4, 5]]

It would be represented as:

one_D = [0, 1, 2, 3, 4, 5]

If he needed to know what was in position (1,1) of the 2D array he would do some simple algebra and get 4.

Is there any performance boost gained by using a 1D array rather than a 2D array. The data in the arrays can be called millions of times during the computation.

I hope the explanation of the data structure is clear...if not let me know and I'll try to explain it better.

Thank you :)

EDIT The language is C


Solution

  • Take a look at Performance of 2-dimensional array vs 1-dimensional array