The standard line on OOP features in Fortran is that they are good for readability and re-use, but bad for execution time. I'm getting mixed results when I test it.
I wrote a simple dummy program to test this by adding two large arrays inside a derived type.
type oop
real(8),allocatable,dimension(:,:,:) :: array
contains
procedure :: plusOOP,eqPlus
generic :: operator(+) => plusOOP
end type
type(oop) function plusOOP(a,b) result(c)
class(oop),intent(in) :: a,b
c%array = a%array+b%array
end function plusOOP
subroutine eqPlus(c,a,b)
class(oop),intent(in) :: a,b
class(oop),intent(inout) :: c
c%array = a%array+b%array
end subroutine eqPlus
I found that call c%eqPlus(a,b)
is just as fast as adding standard arrays. However, this is seems less clear than just writing c%array = a%array+b%array
. Unfortunately, c=a+b
is around two times slower for arrays with more than 1M values. (For arrays with less than 500K values c=a+b
was just as fast but this probably depends on the specific computer.)
Is the real problem with the OOP style the tendency to write everything as functions instead of subroutines? Is there a way to get c=a+b
that doesn't have this overhead for large arrays?