Search code examples
multidimensional-arrayfortranfortran90derived-types

Using 2d array vs array of derived type in Fortran 90


Assuming you want a list of arrays, each having the same size. Is it better performance-wise to use a 2D array :

integer, allocatable :: data(:,:)

or an array of derived types :

type test
    integer, allocatable :: content(:)
end type
type(test), allocatable :: data(:)

Of course, for arrays of different sizes, we don't have a choice. But how is the memory managed between the 2 cases ? Also, is one of them good code practice ?


Solution

  • In general, you want to use the simplest data structure that suits your problem. If a 2d rectangular array meets your needs - and for a huge number of scientific computing problems, problems for which Fortran is a good choice, it does - then that's the choice you want.

    The 2d array will be contiguous in memory, which will normally make accessing it faster both due to caching and one fewer level of indirection; the 2d array will also allow you to do things like data = data * 2 or data = 0. which the array-of-array approach doesn't [Edited to add: though as IanH points out in comments you can create a defined type and defined operations on those types to allow this]. Those advantages are great enough that even when you have "ragged arrays", if the range of expected row lengths isn't that large, implementing it as a rectangular 2d array is sometimes a choice worth considering.